[Problem]
[Solution]
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 {说明:版权所有,转载请注明出处。 Coder007的博客
public:
bool isValid(string s) {
// Note: The Solution object is instantiated only once and is reused by each test case.
stack<char> myStack;
for(int i = 0; i < s.size(); ++i){
if(s[i] == ']'){
if(!myStack.empty() && myStack.top() == '['){
myStack.pop();
}
else{
return false;
}
}
else if(s[i] == ')'){
if(!myStack.empty() && myStack.top() == '('){
myStack.pop();
}
else{
return false;
}
}
else if(s[i] == '}'){
if(!myStack.empty() && myStack.top() == '{'){
myStack.pop();
}
else{
return false;
}
}
else{
myStack.push(s[i]);
}
}
return myStack.empty();
}
};