Valid Parentheses

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.

思路:这道题使用栈作为辅助空间。首先如果遍历到左括号则压入栈中,然后当遍历到")"或者"}"或者"]",则做出判断,如果找到对应的左括号时,将这个左括号出栈。依次类推,三个判断条件,随时判断栈是否为空。最后循环遍历结束后,判断栈是不是为空,如果为空则为真,否则就为假。

class Solution {
public:
    bool isValid(string s) {
        stack<char> str;
        int nSize=s.size();
        if(nSize==0)
            return true;
        for(int i=0;i<nSize;i++)
        {
            if(s[i]=='('||s[i]=='['||s[i]=='{')
                str.push(s[i]);
            else
            {
                if(s[i]==')')
                {
                    if(!str.empty()&&str.top()=='(')
                        str.pop();
                    else
                        return false;
                }
                if(s[i]==']')
                {
                    if(!str.empty()&&str.top()=='[')
                        str.pop();
                    else
                        return false;
                }
                if(s[i]=='}')
                {
                    if(!str.empty()&&str.top()=='{')
                        str.pop();
                    else
                        return false;
                }
            }
        }
        if(str.empty())
            return true;
        else
            return false;
    }
};
原文地址:https://www.cnblogs.com/awy-blog/p/3654633.html