题目:
判断括号是否对称
给定一个值包括’(’、’)’、’[’、’]’、’{’、’}'的字符串,判断字符串是否有效。
有效字符串需满足:
1、左括号必须用相同类型的右括号闭合。
2、左括号必须以正确的顺序闭合。
注意空字符串可别认为是有效字符串
答案:
public class Test {
public static void main(String[] args) {
// 测试代码
System.out.println(isDuiCheng("{}[]"));
System.out.println(isDuiCheng("{[]}"));
System.out.println(isDuiCheng("[{]}"));
}
// 判断是否符合条件要求
private static boolean isDuiCheng(String s) {
// 用于判断里面是否有()[]{}
int count = 0;
// 创建栈对象
Stack<Integer> stack = new Stack<>();
// 遍历字符串中的每一个字符
for (int i = 0; i < s.length(); i++) {
// 获取字符串中的字符
char c = s.charAt(i);
// 获取字符所代表的数字
int number = number(c);
// 如果字符是(、[、{中的任意一个
if (number < 0) {
count++;
// 把(、[、{放进栈里面
stack.push(number);
} else if (number > 0) {
count++;
// 如果栈里面没有(、[、{,那就直接返回false
if (stack.isEmpty()) return false;
// 如果栈顶的字符和该字符不对应,那就直接返回false
if (number + stack.peek() != 0) return false;
// 如果栈顶的字符和该字符对应,那就移除栈顶字符
stack.pop();
}
}
// 如果字符串里面有()[]{},并且栈不是空的,那就直接返回true
return count != 0 && stack.isEmpty();
}
// 把()[]{}变成相应的数字,便于判断和比较
private static int number(char c) {
switch (c) {
case '(':
return -1;
case ')':
return 1;
case '[':
return -2;
case ']':
return 2;
case '{':
return -3;
case '}':
return 3;
default:
return 0;
}
}
}
结果:
true
true
false