"020-valid parentheses (bracket validation)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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.
Main Topic
Given a string containing only (', ') ', ' {', '} ', ' [' and '] ', verify that it is valid. The parentheses must be paired and in the correct order.
Thinking of solving problems
Use a stack to handle the input bracket string, if the left parenthesis on the stack, if the right parenthesis with the top element of the stack to see if a pair of parentheses, the composition will pop up, and processing the next input parenthesis, if the mismatch will directly return the result.
Code Implementation
Import java.util.*; Public classSolution { PublicBoolean isValid (String s) {deque<character>Stack=NewLinkedlist<> ();intindex =0; Character top; while(Index < s.length ()) {Character c = s.charat (index);Switch(c) { Case ' (': Case ' [': Case ' {':Stack. AddFirst (c); Break; Case ' ) ':if(Stack. IsEmpty ()) {return false; } top =Stack. GetFirst ();if(top = =' (') {Stack. Removefirst (); }Else if(top = =' ['|| top = =' {') {return false; }Else{Stack. AddFirst (c); } Break; Case '] ':if(Stack. IsEmpty ()) {return false; } top =Stack. GetFirst ();if(top = =' [') {Stack. Removefirst (); }Else if(top = =' ('|| top = =' {') {return false; }Else{Stack. AddFirst (c); } Break; Case '} ':if(Stack. IsEmpty ()) {return false; } top =Stack. GetFirst ();if(top = =' {') {Stack. Removefirst (); }Else if(top = =' ['|| top = =' (') {return false; }Else{Stack. AddFirst (c); } Break;default:return false; } index++; }return Stack. IsEmpty (); }}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/46997247"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java implementation" "020-valid parentheses (bracket verification)"