Valid parentheses
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 "()" "()[]{}" "(]" "([)]" .
SOLUTION1:
Use stack to solve a simple problem. All the characters go in the stack sequentially
1. If you encounter a pair of brace stacks, the stack does not return false.
2. The stack is empty and can only be pressed into the left parenthesis
3. When the scan is complete, the stack should be empty, otherwise it will return false.
View Code
Solution 2:
It is easier to use a stack resolution. When you push the closing parenthesis, check that the opening parenthesis is not present and returns false if not, or an opening parenthesis is popped.
Finally, whether the stack is empty, not NULL for the number of parentheses asymmetric, also to return false;
1 Public classSolution {2 Public BooleanIsValid (String s) {3 if(s = =NULL) {4 return false;5 }6 7 intLen =s.length ();8 9 //bug 1:don ' t use s as the name of the stack.Tenstack<character> STK =NewStack<character>(); One A for(inti = 0; i < Len; i++) { - Charc =S.charat (i); - Switch(c) { the Case‘(‘: - Case‘[‘: - Case‘{‘: - Stk.push (c); + Break; - Case‘)‘: + if(!stk.isempty () && stk.peek () = = ' (') { A Stk.pop (); at}Else { - return false; - } - Break; - Case‘}‘: - if(!stk.isempty () && stk.peek () = = ' {') { in Stk.pop (); -}Else { to return false; + } - Break; the Case‘]‘: * if(!stk.isempty () && stk.peek () = = ' [') { $ Stk.pop ();Panax Notoginseng}Else { - return false; the } + Break; A } the } + - returnstk.isempty (); $ } $}View Code
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/stack/IsValid.java
Leetcode:valid Parentheses Problem Solving report