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 "()"
"()[]{}"
"(]"
"([)]"
.
Test Instructions: given a string, by,,,, ‘(‘
‘)‘
‘{‘
‘}‘
‘[‘
and‘]‘组成,判断这串字符串是不是有效的组合。
思路:使用栈来解决此题。遍历字符串,如果第一个字符为)} ]中的一个则直接返回false;否则将其压入栈中。接着处理下面的字符:
(1)如果是( { [中的一个则直接压入栈中
(2)如果是})]中的一个,则和栈顶元素比较:如果栈顶元素是遇到元素的匹配字符则栈顶元素出栈,否则返回false
最后判断栈是否为空,如果为空则返回true,否则返回false。
代码:
Public BooleanIsValid (String s) {stack stack=NewStack (); if(S.length () <2)return false; String Temp= string.valueof (S.charat (0)); if(Temp.equals (")") | | Temp.equals ("}") | | Temp.equals ("]"))return false; for(intI=0;i<s.length (); i++) {Temp=string.valueof (S.charat (i)); if(Temp.equals (") | | Temp.equals ("{") | | Temp.equals ("[") {Stack.push (temp); } Else if(!Stack.isempty ()) { Switch(temp) { Case")": if(("("). Equals (Stack.peek ())) {Stack.pop (); }Else { return false; } Break; Case"}": if(("{"). Equals (Stack.peek ())) {Stack.pop (); }Else { return false; } Break; Case"]": if(("["). Equals (Stack.peek ())) {Stack.pop (); }Else{ return false; } Break; default: return false; } } Else { return false; } } // for if(Stack.isempty ()) {return true; }Else { return false; } }
Leetcode (): Valid parentheses