博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
栈的应用题(1)
阅读量:4048 次
发布时间:2019-05-25

本文共 1108 字,大约阅读时间需要 3 分钟。

Given a string containing just the characters '('')''{''}''[' and ']', determine if the input string is valid.

The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]" are not.

关键点:

1)stack<char>的数据结构,stk.push(elem),stk.pop(),stk.top等用法。

2)栈为空,输入为左括弧,输入为右括弧,分不同情况讨论,入栈,出栈,退出,continue等

class Solution {

public:
    bool correct_pair(char elem,char elem2)
    {
        if(((elem    ==  '(')&&(elem2    ==  ')'))||((elem    ==  '[')&&(elem2    ==  ']'))||((elem    ==  '{')&&(elem2    ==  '}')))
            return  true;
        else
            return  false;
    }
    bool isbegin(char   s)
    {
        if((s    ==  '(')||(s    ==  '{')||(s    ==  '['))
            return  true;
        else
            return  false;
    }
    bool is_end(char   s)
    {
        if((s    ==  ')')||(s    ==  '}')||(s    ==  ']'))
            return  true;
        else
            return  false;
    }
    bool isValid(string s) {
        int n   =   s.size();
        stack<char> stk;
        if(0    ==  n)
        {
            return  true;
        }
        for(int i   =   0;i <   n;i++)
        {
            if(0    ==  stk.size())
            {
                stk.push(s[i]);
                continue;
            }
            if(isbegin(s[i]))
            {
                stk.push(s[i]);
            }
            else if(is_end(s[i]))
            {
                if(correct_pair(stk.top(),s[i]))
                {
                    stk.pop();
                    continue;
                    //s.push(s[i]);
                }
                else
                    return  false;
            }
        }
        if(0    ==  stk.size())
            return true;
        else
            return  false;
    }
};

转载地址:http://npbci.baihongyu.com/

你可能感兴趣的文章
iOS app之间的跳转以及传参数
查看>>
iOS __block和__weak的区别
查看>>
Android(三)数据存储之XML解析技术
查看>>
Spring JTA应用之JOTM配置
查看>>
spring JdbcTemplate 的若干问题
查看>>
Servlet和JSP的线程安全问题
查看>>
GBK编码下jQuery Ajax中文乱码终极暴力解决方案
查看>>
Oracle 物化视图
查看>>
PHP那点小事--三元运算符
查看>>
解决国内NPM安装依赖速度慢问题
查看>>
Brackets安装及常用插件安装
查看>>
Centos 7(Linux)环境下安装PHP(编译添加)相应动态扩展模块so(以openssl.so为例)
查看>>
fastcgi_param 详解
查看>>
Nginx配置文件(nginx.conf)配置详解
查看>>
标记一下
查看>>
IP报文格式学习笔记
查看>>
autohotkey快捷键显示隐藏文件和文件扩展名
查看>>
Linux中的进程
查看>>
学习python(1)——环境与常识
查看>>
学习设计模式(3)——单例模式和类的成员函数中的静态变量的作用域
查看>>