Prefix to Infix Conversion
2024-10-06 20:19:42
Infix : An expression is called the Infix expression if the operator appears in between the operands in the expression. Simply of the form (operand1 operator operand2).
Example : (A+B) * (C-D)
Prefix : An expression is called the prefix expression if the operator appears in the expression before the operands. Simply of the form (operator operand1 operand2).
Example : *+AB-CD (Infix : (A+B) * (C-D) )
Given a Prefix expression, convert it into a Infix expression.
分析:
- Read the Prefix expression in reverse order (from right to left)
- If the symbol is an operand, then push it onto the Stack
- If the symbol is an operator, then pop two operands from the Stack
- Create a string by concatenating the two operands and the operator between them.
- string = (operand1 + operator + operand2)
- And push the resultant string back to Stack
- Repeat the above steps until end of Prefix expression.
class Solution {
boolean isOperator(char x) {
switch (x) {
case '+':
case '-':
case '/':
case '*':
return true;
default:
return false;
}
} String preToInfix(String pre_exp) {
Stack<String> stack = new Stack<>();
int length = pre_exp.length();
for (int i = length - ; i >= ; i--) {
if (isOperator(pre_exp.charAt(i))) {
String op1 = stack.pop();
String op2 = stack.pop(); String temp = "(" + op1 + pre_exp.charAt(i) + op2 + ")";
stack.push(temp);
} else {
stack.push(pre_exp.charAt(i) + "");
}
}
return stack.peek();
}
}
最新文章
- 怎样在Dos里切换盘符
- word中表格加粗某一行
- 爱上MVC系列~过滤器实现对响应流的处理
- [R]R语言里的异常处理与错误控制
- php mongodb类
- Asteroids(最小点覆盖)
- Font-Awesome 体验 鼠标进入图标变大
- 如何安装 Composer
- Swing小技巧总结
- HDFS的Java客户端编写
- 0003-20180422-自动化第三章-python基础学习笔记
- Qt简单项目--加法计算器(详细代码注释)
- [golang] Glide 包管理
- vi 新建文件后保存文件时遇到的问题:E212: 无法打开并写入文件
- npm 如何设置镜像站为淘宝网
- Codeforces 937 D. Sleepy Game(DFS 判断环)
- Java 内存模型基础
- SDOI2017 解题报告
- Delphi 资源文件( .res)
- Android--去除EditText边框,加入下划线