解法
n的使用,来判断是否有数
大步骤是逆序的
代码
import java.util.Stack; class Solution { public int cal(Stack<String> stack) { int res=Integer.parseInt(stack.pop()); boolean flag=true; while(!stack.isEmpty()&&!stack.peek().equals(")")) { String temp=stack.pop(); if(temp.equals("+")){ flag=true; }else if(temp.equals("-")) { flag=false; }else { if(flag) { res+=Integer.parseInt(temp); }else { res-=Integer.parseInt(temp); } } } if(!stack.isEmpty()) stack.pop(); return res; } public int calculate(String s) { char[] chars = s.toCharArray(); Stack<String> stack=new Stack<>(); int curnum=0; int n=0; for(int i=chars.length-1;i>=0;i--) { if(Character.isDigit(chars[i])) { curnum=(chars[i]-'0')*(int)Math.pow(10,n)+curnum; n++; }else if(chars[i]!=' ') { if(n!=0) { stack.push(String.valueOf(curnum)); curnum=0; n=0; } if(chars[i]=='(') { int res = cal(stack); stack.push(String.valueOf(res)); }else { stack.push(String.valueOf(chars[i])); } } } int res=0; if(n!=0) stack.push(String.valueOf(curnum)); res = cal(stack); return res; } }