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: Very simple topic, use stack. Traversing the input string, if the current word identifier the left half of the parentheses, it is pressed into the stack, if the right side of the parentheses, if the stack is empty, then directly return false, if not empty, the top of the stack element, if the corresponding left half parenthesis, then continue the loop, and return false instead.
classSolution { Public: BOOLIsValid (strings) {intSS =s.size (); if(ss%2!=0) return false; Stack<Char>par; for(inti =0; I < SS; i++) { Switch(S[i]) { Case '(': Case '[': Case '{': Par.push (S[i]); Break; Case ')': if(Par.empty () | | par.top ()! ='(')return false; Par.pop (); Break; Case ']': if(Par.empty () | | par.top ()! ='[')return false; Par.pop (); Break; Case '}': if(Par.empty () | | par.top ()! ='{')return false; Par.pop (); Break; default: return false; } } returnPar.empty (); }};
[Leetcode]35. Valid parentheses Valid brackets