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.
Solutions:
class Solution { public: bool isValid(string s) { stack<char> sta; for(int i=0; i<s.length(); i++) { if(s[i]=='(' || s[i] =='[' || s[i] == '{') sta.push(s[i]); else { if(sta.empty()) return false; char temp = sta.top(); sta.pop(); if(s[i] == ')' && temp == '(') continue; else if(s[i] == ']' && temp == '[') continue; else if(s[i] == '}' && temp == '{') continue; else return false; } } if(sta.empty()) return true; return false; } };
原文地址:http://blog.csdn.net/shaya118/article/details/42537673