AcWing 1225. Java中缀表达式思路+递归两种解法
原题链接
中等
作者:
上杉
,
2021-04-14 11:55:08
,
所有人可见
,
阅读 442
类似于计算中缀表达式,|符号将左右两边表达式计算出一个结果、()改变优先级、连续字符后、)后添加+号进行连接
import java.util.*;
public class Main{
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String s = scanner.nextLine().trim();
int i = 0;
LinkedList<StringBuilder> strStack = new LinkedList<>();
LinkedList<Character> oper = new LinkedList<>();
while (i < s.length()){
//oper中可能出现的 (、|、+
char c = s.charAt(i);
if (c == '('){
oper.push('(');
}else if (c == '|'){
if (!oper.isEmpty() && oper.peek() == '+'){
oper.pop();
}
oper.push('|');
}else if (c == ')'){
if (!oper.isEmpty() && oper.peek() == '+'){
oper.pop();
}
while (oper.peek() != '('){
Character pop = oper.pop();
if (pop == '|'){
StringBuilder pop1 = strStack.pop();
StringBuilder pop2 = strStack.pop();
strStack.push(pop1.length() > pop2.length() ? pop1:pop2);
}
}
oper.pop();//将(弹出栈
while (!oper.isEmpty() && oper.peek() == '+'){
StringBuilder pop = strStack.pop();
StringBuilder pop1 = strStack.pop();
pop.append(pop1);
strStack.push(pop);
oper.pop();
}
oper.push('+');
}else {
//i = X
StringBuilder str = new StringBuilder();
while (i < s.length() && s.charAt(i) == 'x'){
str.append('x');
i++;
}
//i!=x
while (!oper.isEmpty() && oper.peek() == '+'){
StringBuilder pop = strStack.pop();
str = str.append(pop);
oper.pop();
}
strStack.push(str);
oper.push('+');
i--;
}
i++;
}
while (!oper.isEmpty()){
Character pop = oper.pop();
if (pop == '|'){
StringBuilder pop1 = strStack.pop();
StringBuilder pop2 = strStack.pop();
strStack.push(pop1.length() > pop2.length() ? pop1:pop2);
}
}
StringBuilder res = new StringBuilder();
while (!strStack.isEmpty() ){
res.append(strStack.poll());
}
System.out.println(res.length());
// System.out.println(strStack.pop());
}
}
递归写法、整个表达式看作在一个整个大括号中,大括号里面计算小括号递归进行、没有括号时|二取1、直接相连等于二者相加
import java.util.*;
public class Main{
static String str;
static int index;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
str = input.nextLine().trim();
System.out.println(dfs());
}
//求一个括号中的表达式的值,我们输入的字符串本身就可以看作实在一个不存在的括号中
public static int dfs(){
int res = 0;//这个括号中的表达式的值
while(index < str.length()){
char c = str.charAt(index);
if(c == '('){
index++;
res += dfs();
index++;
}else if(c == ')'){
return res;
}else if(c == '|'){
index++;
res = Math.max(res,dfs());
}else{
res++;
index++;
}
}
return res;
}
}
好难哦