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.
题解:
括号匹配问题,与出现顺序有关,联想到栈和队列。
Solution 1
1 class Solution { 2 public: 3 bool isValid(string s) { 4 if (s.empty()) 5 return true; 6 stack<char> st; 7 8 for (int i = 0; i < s.size(); ++i) { 9 char cur = s[i]; 10 if (cur == '[' || cur == '(' || cur == '{') { 11 st.push(cur); 12 continue; 13 } 14 if (st.empty()) 15 return false; 16 if (cur == ']' && st.top() != '[' 17 || cur == '}' && st.top() != '{' 18 || cur == ')' && st.top() != '(') 19 return false; 20 st.pop(); 21 } 22 23 return st.empty(); 24 } 25 };