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> st;
        for(int i=0;i<s.length();i++)
        {
            char c=s[i];
            if(c=='(' || c=='[' || c=='{')
                st.push(c);
            else if(st.size()==0return false;
            else
            {
                char c2=st.top();
                if((c2=='(' && c==')') || (c2=='[' && c==']') || (c2=='{' && c=='}'))
                    st.pop();
                else return false;
            }
        }
        if(st.size()>0return false;
        else return true;
    }
}; 
posted @ 2014-05-29 15:46  erictanghu  阅读(101)  评论(0编辑  收藏  举报