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();
}
}

最新文章

  1. 怎样在Dos里切换盘符
  2. word中表格加粗某一行
  3. 爱上MVC系列~过滤器实现对响应流的处理
  4. [R]R语言里的异常处理与错误控制
  5. php mongodb类
  6. Asteroids(最小点覆盖)
  7. Font-Awesome 体验 鼠标进入图标变大
  8. 如何安装 Composer
  9. Swing小技巧总结
  10. HDFS的Java客户端编写
  11. 0003-20180422-自动化第三章-python基础学习笔记
  12. Qt简单项目--加法计算器(详细代码注释)
  13. [golang] Glide 包管理
  14. vi 新建文件后保存文件时遇到的问题:E212: 无法打开并写入文件
  15. npm 如何设置镜像站为淘宝网
  16. Codeforces 937 D. Sleepy Game(DFS 判断环)
  17. Java 内存模型基础
  18. SDOI2017 解题报告
  19. Delphi 资源文件( .res)
  20. Android--去除EditText边框,加入下划线

热门文章

  1. java+上传后的文件展示
  2. windbg双机调试配置[转]
  3. vim 代码块排版
  4. Codeforces 808 E. Selling Souvenirs(三分)
  5. php原生导出简单word表格(TP为例) (原)
  6. dubbo中的group与version的存在意义
  7. 复杂sql语句集锦
  8. Mac下mysql服务端密码重置及环境配置
  9. Oracle登录认证
  10. 安装win10提示“我们无法创建新的分区,也找不到现有分区”