leecode 227
中缀转化为后缀(不含括号版)
//判断是否为数字,效率有点低
public static boolean isNum(String s){
try {
Integer.parseInt(s);
return true;
}catch (NumberFormatException e){
return false;
}
}
//判断是否为数字
public static boolean isNum2(String s){
for (int i=0;i<s.length();i++){
if(i==0 && i!=s.length()-1 && s.charAt(0)=='-') continue;
if(!Character.isDigit(s.charAt(i))){
return false;
}
}
return true;
}
//转化为后缀表达式
public List<String> backTempExp(String s){
List<String> result = new LinkedList<>();
Stack<String> stack=new Stack<>();
for (int i=0;i<s.length();i++){
char c=s.charAt(i);
//数字情况下
if(Character.isDigit(c)){
int k=i+1;
while(k<s.length() && Character.isDigit(s.charAt(k))) k++;
result.add(s.substring(i,k));
i=k-1;
continue;
}
//乘除字符情况下
if(c=='/' || c=='*'){
//注意字符的引号
while (!stack.isEmpty() && (stack.peek().equals("/") || stack.peek().equals("*"))){
result.add(stack.pop());
}
stack.add(String.valueOf(c));
continue;
}
if(c=='+' || c=='-'){
while (!stack.isEmpty() && !isNum(stack.lastElement())){
result.add(stack.pop());
}
stack.add(String.valueOf(c));
continue;
}
}
while (!stack.isEmpty()){
result.add(stack.pop());
}
return result;
}
计算后缀表达式结果
public static int calculate(String s) {
Stack<Integer> stackNum=new Stack<>();
List<String> backTemp=backTempExp(s);
for (String str:backTemp){
if(isNum(str)){
stackNum.add(Integer.parseInt(str));
}else {
int a=stackNum.pop();
int b=stackNum.pop();
switch (str.toCharArray()[0]){
case '+':
stackNum.push(a+b);
continue;
case '-':
stackNum.push(b-a);
continue;
case '*':
stackNum.push(a*b);
continue;
case '/':
stackNum.push(b/a);
continue;
}
}
}
return stackNum.pop();
}
有括号版转换
//转化为后缀表达式
public static List<String> backTempExp(String s){
List<String> result = new LinkedList<>();
Stack<String> stack=new Stack<>();
for (int i=0;i<s.length();i++){
char c=s.charAt(i);
//数字情况下
if(Character.isDigit(c)){
int k=i+1;
while(k<s.length() && Character.isDigit(s.charAt(k))) k++;
result.add(s.substring(i,k));
i=k-1;
continue;
}
//括号的情况下
//左括号直接入栈
if(c=='(') {
stack.add(String.valueOf(c));
continue;
}
//右括号将左括号之前所有输出
if(c==')'){
System.out.println("before_stack:"+stack);
while(!stack.isEmpty() && !stack.peek().equals("(")){
result.add(stack.pop());
}
if(!stack.isEmpty()) stack.pop();
}
//乘除字符情况下
if(c=='/' || c=='*'){
while (!stack.isEmpty() && !stack.peek().equals("(") && (stack.peek().equals("/") || stack.peek().equals("*"))){
result.add(stack.pop());
}
stack.add(String.valueOf(c));
continue;
}
if(c=='+' || c=='-'){
while (!stack.isEmpty() && !stack.peek().equals("(") && !isNum(stack.peek())){
result.add(stack.pop());
}
stack.add(String.valueOf(c));
continue;
}
}
while (!stack.isEmpty()){
result.add(stack.pop());
}
return result;
}