LeetCode Valid Parentheses非常简单的解法

来源:互联网 发布:霓虹灯led动画软件 编辑:程序博客网 时间:2024/05/15 23:53

/******************************************
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.
*************************************************/
非常简单,只需用栈实现即可。

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