import java.util.Scanner;
import java.util.Stack;
public class B{
public static void main(String[] args) {
System.out.println("请输入表达式:");
Scanner sc=new Scanner(System.in);
String str = sc.next();
boolean bool=judge(str);//调用judge函数
if (bool) {
System.out.println("“"+str+"”表达式合法!");
}else {
System.out.println("“"+str+"”表达式不合法!");
}
}
public static boolean judge(String str) {
char[] ch=str.toCharArray();//将字符串转换为字符数组
Stack stack=new Stack();//初始化栈
int index=0;
for(int i=0;i<ch.length;i++) {
if (ch[i]=='('||ch[i]=='{'||ch[i]=='[') {
stack.push(ch[i]);//若为左括号则入栈
index++;//使栈内元素数量加1
}
if (ch[i]==')'||ch[i]=='}'||ch[i]==']') {//若为右括号
switch(ch[i]) {
case ')'://若为“)”
if (index-1<0) {break;}
else {
if((stack.get(index-1).toString()).equals("(")) {
stack.pop();break;//若栈顶元素为“(”,则出栈。
}
}
case '}'://若为“}”
if (index-1<0) {break;}
else{
if((stack.get(index-1).toString()).equals("{")) {
stack.pop();break;//若栈顶元素为“{”,则出栈。
}
}
case ']'://若为“]”
if (index-1<0) {break;}
else{
if((stack.get(index-1).toString()).equals("[")) {
stack.pop();break;//若栈顶元素为“[”,则出栈。
}
}
}
index--;//使栈内元素数量减1
}
}
if (stack.isEmpty()&&index==0) {//若栈为空,且右括号不存在表达式合法。
return true;
}else {
return false;
}
}
}
java括号匹配
于 2022-01-14 21:31:47 首次发布