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.
Solution:
class Solution {
public:
bool isValid(string s) {
stack<char> m;
bool r = true;
for(int i=0;i<s.size();i++){
if('(' == s[i] || '{' == s[i] || '[' == s[i])
m.push(s[i]);
else{
if(m.empty())
return false;
char x = m.top();
if(x + 1 == s[i] || x + 2 == s[i]){
m.pop();
}else{
r = false;
break;
}
}
}
if(r && m.empty()) return true;
else return false;
}
};










网友评论