leetcode: Valid Parentheses
http://oj.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.
思路:
用一个堆栈保存左括号然后匹配即可。
1 class Solution { 2 public: 3 bool isValid(string s) { 4 stack<char> left_pars; 5 const char *p = s.c_str(); 6 7 while (*p != '\0') { 8 if (('(' == *p) || ('[' == *p) || ('{' == *p)) { 9 left_pars.push(*p); 10 } 11 else { 12 if (left_pars.empty()) { 13 return false; 14 } 15 16 char exp_left_par; 17 18 if (')' == *p) { 19 exp_left_par = '('; 20 } 21 else if (']' == *p) { 22 exp_left_par = '['; 23 } 24 else { 25 exp_left_par = '{'; 26 } 27 28 if (left_pars.top() == exp_left_par) { 29 left_pars.pop(); 30 } 31 else { 32 return false; 33 } 34 } 35 36 ++p; 37 } 38 39 return left_pars.empty() ? true : false; 40 } 41 };