匹配()、{}、[] 这三种括号的嵌套关系是否正确
public static boolean BracketMatch(String str) {
Stack<Character> stack = new Stack<>();
for (int i = 0; i < str.length(); i++) {
switch (str.charAt(i)){
case '(': case '[': case '{':
stack.push(str.charAt(i));
break;
case ')': case ']': case '}':
if (stack.empty()) { // 右括号多余
System.out.println(str.charAt(i) + "多余");
return false;
} else {
if (Match(stack.peek(), str.charAt(i)))
stack.pop();
else { // 左右括号不匹配
System.out.println("左右括号不匹配");
return false;
}
}
}
}
return true;
}
public static boolean Match(char ch1, char ch2) {
return (ch1 == '(' && ch2 == ')') ||
(ch1 == '{' && ch2 == '}') ||
(ch1 == '[' && ch2 == ']');
}