1. 算法思路
1.1 把表达式转换为字符串数组,
String biaoda = "(((1+(2)-6))";// 表达式
char biao[] = biaoda.toCharArray();// 将字符串转化成字符数组
1.2 设置一个计数器,左括号+1,右括号-1,表达式中计算完毕后,如果为0表示配对
0;// 计数,左括号 1,右括号 -1,最后总和0则匹配
boolean end = true;// true
1.3 循环遍历表达式字符数组,与“(“,”)”进行对比
// 遍历表达式中所有字符
for (int i = 0; i < biao.length; i++){
// 如果是(则加1,进栈
if (biao[i] == '('){
top++;
}else if (biao[i] == ')'){// 如果是)则-1,出栈
if (!(top == 0)){
top--;
}
else {//top == 0,无左括号却有一个右括号,有一个右括号不匹配
System.out.println("括号不匹配 - -");
end = false;
return;
}
}
}
1.4 遍历完进行判断
// 循环结束时两种可能
if (top == 0 && end){
System.out.println("括号匹配");// 出循环stack空
}
else if (top != 0 && end){
System.out.println("括号不匹配");// 出循环时stack不空
2. 完整代码
package com.tangyuan;
public class ExceptionMatch {
public static void main(String[] args) {
int top = 0;// 计数,左括号 1,右括号 -1,最后总和0则匹配
boolean end = true;// true 表示匹配
String biaoda = "(((1+(2)-6))";// 表达式
char[] biao = biaoda.toCharArray();// 将字符串转化成字符数组
System.out.println("表达式: " + biaoda);
// 遍历表达式中所有字符
for (int i = 0; i < biao.length; i++){
// 如果是(则加1,进栈
if (biao[i] == '('){
top++;
}else if (biao[i] == ')'){// 如果是)则-1,出栈
if (!(top == 0)){
top--;
}
else {//top == 0,无左括号却有一个右括号,有一个右括号不匹配
System.out.println("括号不匹配 - -");
end = false;
return;
}
}
}
System.out.println("----");
// 循环结束时两种可能
if (top == 0 && end){
System.out.println("括号匹配");// 出循环stack空
}
else if (top != 0 && end){
System.out.println("括号不匹配");// 出循环时stack不空