解法
注意转化子问题的时机,可以一时间一块弹出两个元素。
代码
import java.util.Stack; class Solution { public static int calculate(String s) { Stack<String> stack=new Stack<>(); char[] chars = s.toCharArray(); int curnum=0; boolean hasNum=false; for(int i=0;i<chars.length;i++) { if(chars[i]>='0'&&chars[i]<='9') { curnum=curnum*10+chars[i]-'0'; hasNum=true; }else if(chars[i]!=' ') { if(hasNum) { if(!stack.isEmpty()&&(stack.peek().equals("*")||stack.peek().equals("/"))) { String point=stack.pop(); int tempnum=Integer.parseInt(stack.pop()); if(point.equals("*")) { stack.push(String.valueOf(tempnum*curnum)); }else { stack.push(String.valueOf(tempnum/curnum)); } }else { stack.push(String.valueOf(curnum)); } curnum=0; hasNum=false; } stack.push(String.valueOf(chars[i])); } } if(hasNum) { if(!stack.isEmpty()&&(stack.peek().equals("*")||stack.peek().equals("/"))) { String point=stack.pop(); int tempnum=Integer.parseInt(stack.pop()); if(point.equals("*")) { stack.push(String.valueOf(tempnum*curnum)); }else { stack.push(String.valueOf(tempnum/curnum)); } }else { stack.push(String.valueOf(curnum)); } } int res=0; boolean flag=true; for(String str:stack) { if(str.equals("+")) { flag=true; }else if(str.equals("-")) { flag=false; }else { if(flag) res+=Integer.parseInt(str); else res-=Integer.parseInt(str); } } return res; } }