题目链接:https://leetcode.com/problems/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) { if(s.size() == 0) return true; stack<char> st; for(int i = 0; i < s.size(); i++) { if(s[i] == '(' || s[i] == '{' || s[i] == '[') st.push(s[i]); else if(s[i] == ')') { if(!st.empty() && st.top() == '(') st.pop(); else return false; } else if(s[i] == '}') { if(!st.empty() && st.top() == '{') st.pop(); else return false; } else if(s[i] == ']') { if(!st.empty() && st.top() == '[') st.pop(); else return false; } else return false; } return st.empty(); } };