java solution stack and regex


  • 0
    M
    public class Solution {
        public int calculate(String s) {
            int res = 0;
            String[] numbers = s.split("[\\+\\-\\*/]");
            String signs = s.replaceAll("[^\\+\\-\\*/]", "");
            char sign;
            Integer num = new Integer(numbers[0].trim());
            Stack<Integer> stack = new Stack<>();
            stack.push(num);
           
            for (int i = 0; i < signs.length(); i++){
                num = new Integer(numbers[i+1].trim());
                sign = signs.charAt(i);    
                switch(sign){
                    case '+':
                        stack.push(num);
                        break;
                    case '-':
                        stack.push(-num);
                        break;
                    case '/':
                        stack.push(stack.pop()/num);
                        break;
                    default:
                        stack.push(stack.pop()*num);
                }
            }
            while (stack.size() > 0)
                res += stack.pop();
            return res;
        }               
    }
    

Log in to reply
 

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