Description
Given A string containing just the characters,, ‘(‘, ‘)‘
‘{‘
, and ‘}‘
‘[‘
‘]‘
, determine if the input string is valid .
Example
The brackets must close in the correct order, and is all valid but and is not "()"
"()[]{}"
"(]"
"([)]"
.
Challenge
O (n) time, n is the number of parentheses
Problem solving: Parentheses matching problems, using stacks to do relatively simple, the code is as follows:
Public classSolution {/** * @params:a String *@return: Whether the string is a valid parentheses*/ Public Booleanisvalidparentheses (String s) {//Write your code hereStack<character>stack =NewStack<character>(); for(inti = 0; I < s.length (); i++){ if(S.charat (i) = = ' (' | | | S.charat (i) = = ' {' | | s.charat (i) = = ' [') {Stack.push (S.charat (i)); }Else{//before pop, check that the stack is empty. if(!Stack.isempty ()) { Switch(S.charat (i)) { Case‘)‘: if(!stack.pop (). Equals (' (')){ return false; } Break; Case‘]‘: if(!stack.pop (). Equals (' [')){ return false; } Break; Case‘}‘: if(!stack.pop (). Equals (' {')){ return false; } Break; } }Else{ return false; } } } if(Stack.isempty ()) {return true; }Else{ return false; } }}
423. Valid parentheses "Lintcode java"