Given A string containing just the characters ' (', ') ', ' {', '} ', ' [' and '] ', determine if the input string is valid. The brackets must close in the correct order, "()" and "() []{}" is all valid but "(]" and "([)]" is not.
This problem is a typical use of pressure stack to solve problems, there is a valid situation is not stated, we need to consider, is "({[]})" This layer of nesting but
Can exactly match, is also a kind of valid. The way to solve this problem is this: we have a character C in the string s, and if C is not a closing parenthesis, it is pressed into the stack stack.
If C is the right parenthesis, determine if the stack is empty, empty means that there is no left parenthesis, directly return not valid, non-empty to take out the top of the stack character pre to compare, if it is a match
, the character that pops up the top of the stack continues to take the next character in S; if it does not match, the description is not valid and is returned directly. Once we have traversed the string s, note
There is also a situation here, that is, there are still characters in the stack are not matched, that is, the stack is not empty at this time, the description s is not valid, because as long as valid, a
All can be matched so that the opening parenthesis pops up.
Public classSolution { Public BooleanIsValid (String s) {Stack<Character> stack=NewStack<character>(); for(inti=0; I<s.length (); i++){ CharC=S.charat (i); if(c = = ' (' | | c = = ' [' | | c = = ' {')) {Stack.push (c); } Else if(c = = ') ' | | c = = '] ' | | c = = '} '){ if(Stack.empty ()) {return false; } Else{ if((c = = ') ' && stack.peek () = = ' (') | | (c = = '] ' && stack.peek () = = ' [') | | (c = = '} ' && stack.peek () = = ' {') ) {Stack.pop (); } Else{ return false; } } } } if(!Stack.empty ()) { return false; } Else{ return true; } }}
Leetcode-valid parentheses