My Accepted Java Solution


  • 0
    O
    public class Solution {
        public int calculate(String s) {
          Queue<Character> q = new LinkedList<Character>();  //for '+' and '-'
          Stack<Character> o = new Stack<Character>();   //for '*' and '/'
          String temp = "0";
          int a = 0;
          int b = 0;
          int r = 0;
          s = s + '+';   // for calculate the last digit
          for(int i = 0; i < s.length(); i++){
             char x = s.charAt(i);
             if(Character.isDigit(x)){
                temp += x;
             }
             else if(x != ' '){
                b = a;
                a = Integer.parseInt(temp);
                temp = "0";
                if(!o.empty()){   //calculate as long as there is '*' or '/'
                    if(o.peek() == '*'){
                      a = b * a;   
                    }else{
                      a = (int) (b / a); 
                    }
                    o.pop();
                }
                if(q.size() ==0)
                   r = a; 
                if(x == '*' || x == '/'){
                   o.push(x);
                }
                if(x == '+' || x == '-'){
                   if(q.size() >0){  //calculate only when it's the second '+' or '-' 
                      if(q.peek() == '+'){
                         r += a;
                      }
                      else{
                         r -= a;
                      }
                      q.remove();
                   }
                   q.add(x);
                }
            }
        }
         return r;
       }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.