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 isValid(std::string s) { const int size = s.size(); std::stack<char> v; if (size % 2) { return false; } else if (size == 0) { return true; } for (int i = 0; i < size; ++i) { const char tmp = s[i]; if (tmp == '(' || tmp == '{' || tmp == '[') { v.push(tmp); } else if ((!v.empty()) && ((tmp == ')' && v.top() == '(') || (tmp == ']' && v.top() == '[') || (tmp == '}' && v.top() == '{'))) { v.pop(); } else { return false; } } return v.empty(); } };在判断的时候也可以使用ASCII码的差值来判断,因为所要匹配的各个ASCII码值为:(--->40、)--->41、[--->91、 ]--->93、{--->123、 }---->125所以可以通过判断ASCII的差值是否等于1或者2来得到答案,这个判断思路是在LeetCode的答案区看到的,当时他的代码是这样写的:
bool isValid(string s) { stack<char> pare; for(auto c:s){ if(c=='(' || c=='{' || c=='['){ pare.push(c); }else{ if(pare.empty()) return false; if(c-pare.top()>2) return false; //becasue in Ascii, (:40, ):41, [:91, ]:93, {:123, }:125 pare.pop(); } } return pare.empty(); }
LeetCode之20---Valid Parentheses
原文:http://blog.csdn.net/jung_zhang/article/details/51170847