Java clean modular solution


  • 0
    A
    public int calculate(String s) {
    	return evaluatePostfix(infixToPostfix(tokenize(s)));
    }
    
    int evaluatePostfix(List<String> postfix) {
    	Stack<String> st = new Stack<String>();
    	for (String token : postfix) {
    		if (token.equals("+")) {
    			int b = Integer.parseInt(st.pop());
    			int a = Integer.parseInt(st.pop());
    			st.push(String.valueOf(a + b));
    		} else if (token.equals("-")) {
    			int b = Integer.parseInt(st.pop());
    			int a = Integer.parseInt(st.pop());
    			st.push(String.valueOf(a - b));
    		} else
    			st.push(token);
    	}
    	return Integer.parseInt(st.pop());
    }
    
    List<String> infixToPostfix(List<String> infix) {
    	Stack<String> st = new Stack<String>();
    	List<String> postfix = new LinkedList<String>();
    	for (String token : infix) {
    		if (token.equals("("))
    			st.push(token);
    		else if (token.equals(")")) {
    			while (!st.peek().equals("("))
    				postfix.add(st.pop());
    			st.pop();
    		} else if (token.equals("+") || token.equals("-")) {
    			while (!st.isEmpty() && !st.peek().equals("("))
    				postfix.add(st.pop());
    			st.push(token);
    		} else
    			postfix.add(token);
    	}
    	while (!st.isEmpty())
    		postfix.add(st.pop());
    	return postfix;
    }
    
    List<String> tokenize(String s) {
    	List<String> tokens = new LinkedList<String>();
    	int i = 0;
    	while (i < s.length()) {
    		if (s.charAt(i) == ' ')
    			while (i < s.length() && s.charAt(i) == ' ') i++;
    		else if (s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '(' || s.charAt(i) == ')')
    			tokens.add(String.valueOf(s.charAt(i++)));
    		else if (Character.isDigit(s.charAt(i))) {
    			int start = i;
    			while (i < s.length() && Character.isDigit(s.charAt(i))) i++;
    			tokens.add(s.substring(start, i));
    		}
    	}
    	return tokens;
    }

Log in to reply
 

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