title :
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 "()" "()[]{}" "(]" "([)]" .
Exercises
This problem is a very common old problem, remember at that time to see the data structure of Min also have data structures class above have seen this problem, a training stack of the basic problem.
The way to solve this problem is:
Check to the characters, if the left parenthesis are in the stack, if the right parenthesis, check if the stack is empty, the proof can not match, if the stack is not empty, pop top, and the current scan of the parentheses check if the match.
After all the characters have been checked, the judgment stack is empty, the null matches correctly, and the non-empty one proves that there is no match.
Attention:
Check that the character is with = = and check that the string is used with. IsEqual () because string is a reference type and the value is equal but the address may be unequal.
The code is as follows:
1 Public BooleanIsValid (String s) {2 if(S.length () ==0| | S.length () ==1)3 return false;4 5stack<character> x =NewStack<character>();6 for(intI=0;i<s.length (); i++){7 if(S.charat (i) = = ' (' | | S.charat (i) = = ' {' | | S.charat (i) = = ' ['){8 X.push (S.charat (i));9}Else{Ten if(X.size () ==0) One return false; A Chartop =X.pop (); - if(S.charat (i) = = ') ') - if(Top!= ' (') the return false; - Else if(S.charat (i) = = '} ') - if(top!= ' {')) - return false; + Else if(S.charat (i) = = '] ') - if(top!= ' [') + return false; A } at } - returnX.size () ==0; -}
Reference:http://www.cnblogs.com/springfor/p/3869420.html
*valid parentheses