标签:
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.
使用堆栈进行配对即可.
1 bool isValid(string s) 2 { 3 stack<char> stk; 4 for (int i = 0; i < s.size(); i++) 5 { 6 switch(s[i]) 7 { 8 case ‘(‘: 9 case ‘{‘: 10 case ‘[‘: 11 stk.push(s[i]); 12 break; 13 case ‘)‘: 14 if (stk.empty() || stk.top() != ‘(‘) 15 return false; 16 stk.pop(); 17 break; 18 case ‘]‘: 19 if (stk.empty() || stk.top() != ‘[‘) 20 return false; 21 stk.pop(); 22 break; 23 case ‘}‘: 24 if (stk.empty() || stk.top() != ‘{‘) 25 return false; 26 stk.pop(); 27 break; 28 default: 29 return false; 30 } 31 } 32 33 return stk.empty(); 34 }
leetcode 20. Valid Parentheses
标签:
原文地址:http://www.cnblogs.com/ym65536/p/4240203.html