题目:
Given a string containing just the characters , determine if the input string is valid.
The brackets must close in the correct order, “()” and “()[]{}” are all valid but “(]” and “([)]” are not.
翻译:
给定一个字符串,只包含’(‘, ‘)’, ‘{‘, ‘}’, ‘[’ 和’]’这些字符,检查它是否是“有效”的。
括号必须以正确的顺序关闭,例如”()” 和”()[]{}”都是有效的,”(]” 和”([)]”是无效的。
思路:先把一个String存入字符数组,遍历这个数组,当字符为'(','{','['时候,存入Stack中,然后遍历到下个字符时,如果为空则返回false,如果不为空,且当前字符与栈顶为正确数组闭合,则返回true。
代码:
package leetCode;
import java.util.Stack;
public class ValidParentheses {
public boolean isValid(String s){
Stack<Character> st = new Stack<>();
char[] charArr = s.toCharArray();//把s变成字符数组
for(Character a:charArr){
if(a=='('||a=='{'||a=='['){
st.push(a);
}
else {
if(st.isEmpty()){
return false;
}
char last=st.peek();//把栈顶赋值为last
//下面代码都是如果不是正确闭合顺序,返回false
if(a==')'&&last!='('){
return false;
}else if(a=='}'&&last!='{'){
return false;
}else if(a==']'&&last!='['){
return false;
}
st.pop(); //如果正确闭合了则把栈顶去掉
}
}
if(!st.empty()){ //这种情况只会出现在最后一个字符是'}', ]’,')'
return false;
}
return true;
}
public static void main(String[] args) {
String s = "[]{}()";
boolean b = new ValidParentheses().isValid(s);
System.out.println(b);
}
}