Valid Parentheses
Total Accepted: 84022 Total Submissions: 301663 Difficulty: Easy
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.
class Solution {
public:
bool isValid(string s) {
vector<int> vec;
int len=s.length();
int i=0;
while(i<len){
if(s[i]=='('||s[i]=='{'||s[i]=='['){
vec.push_back(s[i]);
}else{
if(s[i]==')'){
if(vec.size()>0&&vec.back()=='('){
vec.pop_back();
}else{
return false;
}
}else if(s[i]=='}'){
if(vec.size()>0&&vec.back()=='{'){
vec.pop_back();
}else{
return false;
}
}else if(s[i]==']'){
if(vec.size()>0&&vec.back()=='['){
vec.pop_back();
}else{
return false;
}
}
}
i++;
}
if(vec.size()==0){
return true;
}else{
return false;
}
}
};