给定一个只包括 '('
,')'
,'{'
,'}'
,'['
,']'
的字符串,判断字符串是否有效。
有效字符串需满足:
- 左括号必须用相同类型的右括号闭合。
- 左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
示例 1:
输入: "()" 输出: true
示例 2:
输入: "()[]{}" 输出: true
示例 3:
输入: "(]" 输出: false
示例 4:
输入: "([)]" 输出: false
示例 5:
输入: "{[]}" 输出: true
解题思路,将左边括号全部放入栈,当遇到右边的括号,与栈的顶层元素进行匹配。
public boolean isValid(String s) {
int length=s.length();
if(length==0) {//空字符串输出true
return true;
}
Stack<String> stack=new Stack<String>();
boolean res=false;
String temp=null;
for(int i=0;i<length;i++) {
temp=s.substring(i, i+1);//获取当前字符,看是否是右半边
if(temp.equals(")")||temp.equals("}")||temp.equals("]")) {
if(stack.empty()) {
return false;
}
res=matching(stack.pop(),temp);
if(!res) {//一旦匹配有错,直接返回
return false;
}
}else {
stack.push(s.substring(i, i+1));
}
}
//匹配完成后,stack应该是空的,不为空则表示有错误。
if(stack.isEmpty()) {
return true;
}
return false;
}
public static boolean matching(String left, String right) {
if(left.matches("\\(")&&right.matches("\\)")) {
return true;
}else if(left.matches("\\{")&&right.matches("\\}")) {
return true;
}else if(left.matches("\\[")&&right.matches("\\]")) {
return true;
}else if(left.matches("\"")&&right.matches("\"")) {
return true;
}
return false;
}