Valid Parentheses

方法:直接使用栈的数据结构对相关字符处理即可

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

 

posted @ 2017-04-26 08:41  chengcy  Views(101)  Comments(0)    收藏  举报