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: iterate the string, find the matching s[i] and s[i+1].
class Solution {
public:
bool isBracket(const char a, const char b){
if(a == '(' && b == ')')
return true;
else if(a == '[' && b == ']')
return true;
else if(a == '{' & b == '}')
return true;
else
return false;
}
bool isValid(string s) {
for(int i = 0; i < s.size() - 1 && s.size() > 0;){
if(isBracket(s[i], s[i+1])){
s.erase(i, 2);
if(i > 0 && s.size() > 0){
i--;
}
}
else{
i++;
}
}
return s.size() == 0 ? true: false;
}
};