Use Tokenizer - easy two passes, hassle free


  • 0
    F
    public int calculate2(String s) {
        LinkedList<String> list = new LinkedList<>();
        StringTokenizer st = new StringTokenizer(s, " +-*/", true);
        // remove */
        while (st.hasMoreTokens()) {
            String cur = st.nextToken();
            switch (cur) {
                case " ":
                    break;
                case "+":
                case "-":
                    list.addLast(cur);
                    break;
                case "*":
                case "/":
                    String next = st.nextToken();
                    while(next.equals(" ")) {
                        next = st.nextToken();
                    }
                    String prev = list.removeLast();
                    list.addLast(createNew(prev, next, cur));
                    break;
                default:
                    list.addLast(cur);
                    break;
            }
        }
        // now list only contains numbers and +-
        Iterator<String> itr = list.iterator();
        int ret = 0;
        boolean plus = true;
        while (itr.hasNext()) {
            String cur = itr.next();
            switch (cur) {
                case "+":
                    plus = true;
                    break;
                case "-":
                    plus = false;
                    break;
                default:
                    int right = Integer.parseInt(cur);
                    ret = plus ? ret + right : ret - right;
                    break;
            }
        }
        return ret;
    }
    
    String createNew(String left, String right, String op) {
        int iLeft = Integer.parseInt(left);
        int iRight = Integer.parseInt(right);
        if (op.equals("*")) {
            return "" + (iLeft * iRight);
        } else {
            return "" + (iLeft / iRight);
        }
    }

Log in to reply
 

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