Simple Java Solution using RegExp without Stack/Queue


  • 0

    I seperate the string to operators and nums.

    1. Iterate operators .
    • If we get * or /, set the first num to zero and the second num to the calculation result;
    • If we get -, set the num to negative.
    1. Add up all nums.
       public int calculate(String s) {
            s=s.replaceAll("\\s+","");
            String[] numsstr=s.split("[^0-9]");
            int[] nums=new int[numsstr.length];
            for(int i=0;i<nums.length;i++)
                nums[i]=Integer.parseInt(numsstr[i]);
            String[] ops=("+"+s).split("[0-9]+");
            for(int i=0;i<ops.length;i++){
                if(ops[i].equals("*")){
                    nums[i]=nums[i-1]*nums[i];
                    nums[i-1]=0;
                }else if(ops[i].equals("/")){
                    nums[i]=nums[i-1]/nums[i];
                    nums[i-1]=0;
                }else if(ops[i].equals("-"))
                    nums[i]=-nums[i];
            }
            int res=0;
            for(int i:nums)
                res+=i;
            return res;
        }

Log in to reply
 

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