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.
idea: go through the string. use a stack to store the '(''[''{'. then, if it is ')'']''}', check the stack.
The key of this question is how to use stack.
class Solution {
public:
bool isValid(string s) {
bool flag = false;
if(s.size() <= 1) return flag;
if(s.size() % 2 == 1) return flag;
stack <char> myStack;
for(int i = 0; i < s.size(); i++ ){
if(s[i] == '(' || s[i] == '[' || s[i] == '{'){
myStack.push(s[i]);
}else{
if(myStack.empty()) return false;
char back = myStack.top();
if(back == '('){
if(s[i] != ')') return false;
else myStack.pop();
}
else if(back == '['){
if(s[i] != ']') return false;
else myStack.pop();
}
else if(back == '{'){
if(s[i] != '}') return false;
else myStack.pop();
}
}
}
if(myStack.empty()) return true;
else return false;
}
};