Created
August 9, 2019 04:44
-
-
Save shixiaoyu/333d6e15d20910b7e2447aff9df80b3a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int calculate(String s) { | |
if (s == null || s.length() == 0) { | |
throw new IllegalArgumentException("Invalid input"); | |
} | |
int i = 0; | |
Stack<Integer> operands = new Stack<>(); | |
Stack<Character> operators = new Stack<>(); | |
StringBuilder number = new StringBuilder(); | |
while (i < s.length()) { | |
char c = s.charAt(i); | |
if (c == ' ') { | |
i++; | |
continue; | |
} | |
if (Character.isDigit(c)) { | |
number.append(c); | |
} else if (c == '(') { | |
operators.push(c); | |
} else if (c == ')') { | |
// push the current number to the operands stack | |
if (number.length() != 0) { | |
operands.push(Integer.parseInt(number.toString())); | |
number = new StringBuilder(); | |
} | |
if (!operators.isEmpty() && operators.peek() != '(') { | |
char op = operators.pop(); | |
operands.push(this.calculateValue(operands, op)); | |
} | |
if (!operators.isEmpty()) { // pop the left bracket | |
operators.pop(); | |
} | |
} else if (c == '+' || c == '-') { | |
if (number.length() != 0) { | |
operands.push(Integer.parseInt(number.toString())); | |
number = new StringBuilder(); | |
} | |
if (!operators.isEmpty() && operators.peek() != '(') { | |
operands.push(this.calculateValue(operands, operators.pop())); | |
} | |
operators.push(c); | |
} | |
i++; | |
} | |
if (number.length() != 0) { | |
operands.push(Integer.parseInt(number.toString())); | |
} | |
// need this for the 1+1 case, don't need a while since we are only one step away | |
if (!operators.isEmpty()) { | |
operands.push(this.calculateValue(operands, operators.pop())); | |
} | |
return operands.pop(); | |
} | |
private int calculateValue(Stack<Integer> operands, char operator) { | |
// Pay attention to the stack order | |
int o2 = operands.pop(); | |
int o1 = operands.pop(); | |
if (operator == '+') { | |
return o1 + o2; | |
} else if (operator == '-') { | |
return o1 - o2; | |
} else { | |
throw new IllegalArgumentException("invalid operator!"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment