Given a string containing just the characters '('
, ')'
, '{'
, '}'
, '['
and ']'
, determine if the input string is valid.
An input string is valid if:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
Example 1:
Input: "()" Output: true
Example 2:
Input: "()[]{}" Output: true
Example 3:
Input: "(]" Output: false
Example 4:
Input: "([)]" Output: false
Example 5:
Input: "{[]}" Output: true
括号匹配--->栈
class Solution {
public boolean isValid(String s) {
Stack<Character> check=new Stack<Character>();
char[] s1=s.toCharArray();
for(int i=0;i<s.length();i++){
if(s1[i]=='('||s1[i]=='['||s1[i]=='{'){
check.push(s1[i]);
}
else{
switch(s1[i]){
case ')':{
if(check.isEmpty()) return false;
if(check.pop()!='(') return false;
break;
}
case ']':{
if(check.isEmpty()) return false;
if(check.pop()!='[') return false;
break;
}
case '}':{
if(check.isEmpty()) return false;
if(check.pop()!='{') return false;
break;
}
}
}
}
if(check.isEmpty()) return true;
else return false;
}
}
注意注意,不要和python混了
Java里变量在使用之前需要new出来,并且对于字符串不能直接使用下标访问,要使用toCharArray( )将字符串转化为字符数组。
在讨论区看到另一种同样是用栈的方法,在左括号的情况将对应的右括号push进去
public boolean isValid(String s) {
Stack<Character> stack = new Stack<Character>();
for (char c : s.toCharArray()) {
if (c == '(')
stack.push(')');
else if (c == '{')
stack.push('}');
else if (c == '[')
stack.push(']');
else if (stack.isEmpty() || stack.pop() != c)
return false;
}
return stack.isEmpty();
}