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 "()"
"()[]{}"
"(]"
"([)]"
.
Public classSolution { Public BooleanIsValid (String s) {//Solving : Need auxiliary stack to judge, time complexity is O (n), space complexity is O (n)//when the opening parenthesis is encountered, the right parenthesis needs to be judged: 1. Whether the stack is empty, 2. Whether the top of the stack matches this symbol. Returns False if there is a condition mismatch//Note the following details://1. Need to determine the stack when the stack empty//2. Final return results need to determine whether the stack is emptyStack<character> stack=NewStack<character>(); for(intI=0;i<s.length (); i++){ Chartemp=S.charat (i); if(temp== ' (' | | | temp== ' {' | | | temp== ' [') Stack.push (temp); Else{ if(temp== ') '){ if(!stack.empty () && (Char) Stack.peek () = = ' (') Stack.pop (); Else return false; } if(temp== ') '){ if(!stack.empty () && (Char) Stack.peek () = = ' [') Stack.pop (); Else return false; } if(temp== '} '){ if(!stack.empty () && (Char) Stack.peek () = = ' {') Stack.pop (); Else return false; } } } returnStack.empty (); }}
[Leedcode 20] Valid parentheses