这道题跟227题,背下来!
Iterative:
class Solution { public int calculate(String s) { s=s.replace(" ", "")+'+'; Stack<Integer> stk = new Stack<>(); int sign =1; int num=0; int res = 0; for(int i=0;i<s.length();i++){ char c = s.charAt(i); if(Character.isDigit(c)){ num = num*10+c-'0'; } else{ if(c=='+'){ res+=sign*num; num=0; sign=1; }else if(c=='-'){ res+=sign*num; num=0; sign=-1; }else if(c=='('){ stk.push(res); stk.push(sign); res=0; sign=1; }else if(c==')'){ res += sign*num; res*=stk.pop(); res+=stk.pop(); num=0; } } } return res; } }
Recursive:
class Solution { public int calculate(String s) { s=s.replace(" ", ""); Queue<Character> queue = new LinkedList<>(); for(int i=0;i<s.length();i++){ queue.offer(s.charAt(i)); } return helper(queue); } private int helper(Queue<Character> queue){ Stack<Integer> stk = new Stack<>(); int num =0; int sign=1; int res = 0; while(!queue.isEmpty()){ char c = queue.poll(); if(Character.isDigit(c)){ num=num*10+c-'0'; }else{ if(c=='+'){ res+=sign*num; num=0; sign=1; } else if(c=='-'){ res+=sign*num; num=0; sign=-1; }else if(c=='('){ res+=sign*helper(queue); }else { break; } } } return res+sign*num; } }