标签:style blog color os io for ar div
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> S; 5 for(int i = 0; i < s.length(); i++){ 6 if(!S.empty()){ 7 char top = S.top(); 8 if(pair(top,s[i])) S.pop(); 9 else S.push(s[i]); 10 }else S.push(s[i]); 11 } 12 if(S.empty()) return true; 13 return false; 14 } 15 bool pair(char l, char r){ 16 if(l == ‘(‘ && r == ‘)‘) return true; 17 if(l == ‘[‘ && r == ‘]‘) return true; 18 if(l == ‘{‘ && r == ‘}‘) return true; 19 return false; 20 } 21 };
Valid Parentheses,布布扣,bubuko.com
标签:style blog color os io for ar div
原文地址:http://www.cnblogs.com/Kai-Xing/p/3902745.html