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) { // Start typing your C/C++ solution below // DO NOT write int main() function int l1=0,l2=0,l3=0; for(int i=0;i<s.length();i++){ if(s[i]=='(')l1++; else if(s[i]=='[')l2++; else if(s[i]=='{')l3++; else{ if(s[i]==')'){ if(l1==0)return false; else l1--; if(s[i-1]=='['||s[i-1]=='{')return false; } else if(s[i]==']'){ if(l2==0)return false; else l2--; if(s[i-1]=='('||s[i-1]=='{')return false; } else if(s[i]=='}'){ if(l3==0)return false; else l3--; if(s[i-1]=='['||s[i-1]=='(')return false; } } } if(l1>0||l2>0||l3>0)return false; return true; } };