Easy Understand Java Solution


  • 0
    Q

    My idea: treat the string by " a op1 b op2 c " form.

    public int calculate(String s) {
        s = s.replaceAll(" ","");
    
        int len = s.length();
    
        int a = 0;
        int b = 0;
        int c = 0;
        char op1 = '+';
        char op2 = '+';
    
        int idx = 0;
    
        while(idx<len){
    
            char ch = s.charAt(idx);
            if(Character.isDigit(ch)){
                //If ch is digit
                int cur = 0;
                while(idx<len && Character.isDigit(s.charAt(idx))){
                    cur *= 10;
                    cur += s.charAt(idx)-'0';
                    idx++;
                }
                c = cur;
    
                if(op2=='*' || op2=='/'){
                    b = count(b,c,op2);
                    op2 = '+';
                    c = 0;
                } else{
                    a = count(a,b,op1);
                    b = c;
                    op1 = op2;
                    op2 = '+';
                    c = 0;
                }
            } else{
                // If ch is operator
                op2 = ch;
                idx++;
            }
        }
    
        if(priority(op1)>=priority(op2)){
            return count(count(a,b,op1),c,op2);
        } else{
            return count(a,count(b,c,op2),op1);
        }
    }
    
    int priority(char op){
        if(op=='+' || op=='-')
            return 1;
        else
            return 2;
    }
    
    int count(int a, int b, char c){
        if(c=='+'){
            return a+b;
        } else if(c=='-'){
            return a-b;
        } else if(c=='*'){
            return a*b;
        } else{
            return a/b;
        }
    }

Log in to reply
 

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