Given A string containing just the characters,,, ‘(‘
‘)‘
, and ‘{‘
‘}‘
‘[‘
‘]‘
, determine if the input string I S valid.
The brackets must close in the correct order, and is all valid but and is not "()"
"()[]{}"
"(]"
"([)]"
.
Solution:
1 classSolution {2 Public:3 BOOLIsValid (strings) {4 if(S.size () <2)return false;5stack<Char>Stk;6 for(intI=0; I<s.size (); i++){7 if((s[i]=='(')|| (s[i]=='[')|| (s[i]=='{') ) Stk.push (S[i]);8 if((s[i]=='}')|| (s[i]==']')|| (s[i]==')')){9 if(Stk.empty ())return false;Ten CharC=stk.top (); One Stk.pop (); A Switch(S[i]) { - Case '}':if(c!='{')return false; Break; - Case ')':if(c!='(')return false; Break; the Case ']':if(c!='[')return false; Break; - } - } - } + if(!stk.empty ())return false; - return true; + } A};
Better solution:
1 classSolution {2 Public:3 BOOLIsValid (strings) {4stack<Char>Paren;5 for(Char&c:s) {6 Switch(c) {7 Case '(': 8 Case '{': 9 Case '[': Paren.push (c); Break;Ten Case ')':if(Paren.empty () | | paren.top ()! ='(')return false;ElseParen.pop (); Break; One Case '}':if(Paren.empty () | | paren.top ()! ='{')return false;ElseParen.pop (); Break; A Case ']':if(Paren.empty () | | paren.top ()! ='[')return false;ElseParen.pop (); Break; - default: ;//Pass - } the } - returnparen.empty (); - } -};
Valid parentheses (c + +)