leetcode - 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 isPair(char a, char b){ if(a == ‘(‘ && b == ‘)‘) return true; if(a == ‘[‘ && b == ‘]‘) return true; if(a == ‘{‘ && b == ‘}‘) return true; return false; } bool isValid(string s) { stack<char> strStk; int i=0; while(i<s.length()){ if(!strStk.empty()){ if(isPair(strStk.top(), s[i])) strStk.pop(); else strStk.push(s[i]); } else strStk.push(s[i]); i++; } return strStk.empty() ? true : false; } };
原文:http://www.cnblogs.com/shnj/p/4737302.html