Pretty easy to understand java solution with O(n) space, no stacks used.

  • 2

    public class Solution {

    public int calculate(String s) {
        s = deleteSpaceAndReplace(s);
        String[] plus = s.split("\\+");
        int res = 0;
        for(String subPlus:plus){
            res += computeMD(subPlus);
        return res;     
    public String deleteSpaceAndReplace(String s){
        StringBuilder strbd = new StringBuilder();
        for(int i = 0; i<s.length();i++){
            if(s.charAt(i)==' ') continue;
            if(s.charAt(i)=='-') strbd.append('+'); //these 2 lines are used for making split easier.
            if(s.charAt(i)=='/') strbd.append('*');
        return strbd.toString();
    public int computeMD(String s){ //compute multiply and divide
        if(s.charAt(0)=='-') return -computeMD(s.substring(1,s.length())); //deal with minus
        String[] multi = s.split("\\*");
        int res = 1;
        for(String mul:multi){
            if(mul.charAt(0)!='/') res *= Integer.parseInt(mul);
            else res /= Integer.parseInt(mul.substring(1,mul.length())); //deal with divide
        return res;


Log in to reply

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