笔试题算法实现
最近有很多笔试算法题,碰到了一道很陌生的:波兰表示法和逆波兰表示法的转换,用java代码实现了一下,题解给的实例跑通了,不知道其他的怎么样。
题干如下:
思路
- 从后向前遍历输入的字符数组
- 根据题干中前波的表示方法入栈
- 输出前波的结果,与给出示例表达式对比
- *将正确的前波拆分入栈
- 规则为遇到右括号出栈四项值,分别为:左括号,表达式左值,表达式,表达式右值
- 按后波的规则拼接,并入栈
- 最后栈中的就是结果
java代码如下
#### **写的仓促变量定义有点乱**
import java.util.ArrayList;
import java.util.Stack;
public class Main {
public static void main(String[] args) {
String str="-,+,a,*,+,b,c,d,e";
String[] strs=str.split(",");
Stack<String> stac=new Stack<String>();
ArrayList<String> al=new ArrayList<String>();
al.add("+");al.add("-");al.add("*");al.add("/");// 存放标点值
int i=strs.length-1;
while(i>=0){
if(!al.contains(strs[i])){
stac.push(strs[i]);
}else{
String one=stac.pop();
String two=stac.pop();
String tem="("+one+strs[i]+two+")"; // 全部添加括号保证 下边运算的正确顺序
stac.push(tem);
}
i--;
}
Stack<String> sta1=new Stack<String>();
String[] re=stac.pop().split("");
int j=0;
while(j<re.length){
if(!re[j].equals(")")){
sta1.push(re[j]);
}else{
String one=sta1.pop();
String two=sta1.pop();
String three=sta1.pop();
String four=sta1.pop();// 仅仅是将左括号 去除掉
String tem=""+three+one+two;
sta1.push(tem);
}
j++;
}
System.out.println(sta1.pop());
}
}