lintcode有效的括号序列

来源:互联网 发布:傲来网络 编辑:程序博客网 时间:2024/05/17 20:30

有效的括号序列 

给定一个字符串所表示的括号序列,包含以下字符: '(', ')''{''}','[' and ']', 判定是否是有效的括号序列。

Example

括号必须依照 "()" 顺序表示, "()[]{}" 是有效的括号,但 "([)]"则是无效的括号。

Tags 
Related Problems 
分析:这是一道简单的题,用栈来存左边的符号,遇到栈顶元素和当前准备入栈的元素配对时,弹栈,否则继续入栈。最后依据栈中元素是否为空来判断是否有序
class Solution {public:    /*     * @param s: A string     * @return: whether the string is a valid parentheses     */    bool isValidParentheses(string &s) {        // write your code here        stack<char>coup;        int i=0;        while(i<s.size()){            if(coup.size()>0){//there character in stack                if(s[i]==')')                {                    if(coup.top()=='(')                    {                        coup.pop();                        i++;                        continue;                    }                }                else if(s[i]==']')                {                    if(coup.top()=='['){                    coup.pop();                        i++;                        continue;                    }                }                else if(s[i]=='}')                {                    if(coup.top()=='{')                    {                    coup.pop();                        i++;                        continue;                    }                }            }             coup.push(s[i]);            i++;                }        if(coup.size()>0)        return false;        else        return true;    }};


原创粉丝点击