Valid Parentheses

来源:互联网 发布:印度一夫多妻制 知乎 编辑:程序博客网 时间:2024/06/05 06:34

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.

思路: 使用堆栈,成对就可以弹出,不成对继续入栈,如果栈顶是反括号则不可能成对,直接false.

class Solution {public:    bool isValid(string s) {        stack<char> schar;        //char table[] = "(){}[]";        for(int i = 0; i < s.size(); ++i){            if(schar.empty() ){                schar.push(s[i]);            }else{                switch (schar.top()){                    case '(':                        if(')' == s[i]) schar.pop();                        else schar.push(s[i]);                        break;                    case '{':                        if('}' == s[i]) schar.pop();                        else schar.push(s[i]);                        break;                    case '[':                        if(']' == s[i]) schar.pop();                        else schar.push(s[i]);                        break;                    default: return false;                }            }        }        return schar.empty();    }};
原创粉丝点击