My ugly java stack solution


  • 0
    I
    public class Solution {
        public int calculate(String s) {
            s = s.trim();
            
            Stack<Integer> st = new Stack<Integer>();
            int i = 0;
            while(i < s.length()) {
                while(i < s.length() && Character.isWhitespace(s.charAt(i))) {
                    i++;
                }
                
                if(s.length() == i) {
                    break;
                }
                
                if(s.charAt(i) != '*' && s.charAt(i) != '/') {
                    boolean isNeg = false;
                    if(s.charAt(i) == '-') {
                        isNeg = true;
                        i++;
                    } else if(s.charAt(i) == '+') {
                        i++;
                    }
                    
                    while(Character.isWhitespace(s.charAt(i))) {
                        i++;
                    }
                    
                    String num = "";
                    while(i < s.length() && Character.isDigit(s.charAt(i))) {
                        num += s.charAt(i);
                        i++;
                    }
                    
                    st.push(Integer.parseInt(num) * (isNeg ? -1 : 1));
                } else {
                    char op = s.charAt(i);
                    int res = st.pop();
                    i++;
                    while(Character.isWhitespace(s.charAt(i))) {
                        i++;
                    }
                    
                    String num = "";
                    while(i < s.length() && Character.isDigit(s.charAt(i))) {
                        num += s.charAt(i);
                        i++;
                    }
                    
                    while(i < s.length() && s.charAt(i) == ' ') {
                        i++;
                    }
                    
                    int tmp = Integer.parseInt(num);
                    res = op == '*' ? res * tmp : res / tmp;
                    st.push(res);
                }
            }
            
            int res = 0;
            while(!st.isEmpty()) {
                res += st.pop();
            }
            
            return res;
        }
    }
    

Log in to reply
 

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