美文网首页
20. Valid Parentheses

20. Valid Parentheses

作者: a_void | 来源:发表于2016-09-26 21:26 被阅读0次

    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.

    Solution:

    class Solution {
    public:
        bool isValid(string s) {
            stack<char> m;
            bool r = true;
            for(int i=0;i<s.size();i++){
                if('(' == s[i] || '{' == s[i] || '[' == s[i])
                    m.push(s[i]);
                else{
                    if(m.empty())
                        return false;
                    char x = m.top();
                    if(x + 1 == s[i] || x + 2 == s[i]){
                        m.pop();
                    }else{
                        r = false;
                        break;
                    }
                }
            }
            if(r && m.empty()) return true;
            else return false;
        }
    };
    

    相关文章

      网友评论

          本文标题:20. Valid Parentheses

          本文链接:https://www.haomeiwen.com/subject/fgnqyttx.html