Skip to content

Instantly share code, notes, and snippets.

@shixiaoyu
Created August 9, 2019 04:45
Show Gist options
  • Save shixiaoyu/a0ae3f2435c649899d67687ff61db2f2 to your computer and use it in GitHub Desktop.
Save shixiaoyu/a0ae3f2435c649899d67687ff61db2f2 to your computer and use it in GitHub Desktop.
// The main idea of this is the left bracket might change the sign of a number, however, this does not seem to be very generalized
// https://leetcode.com/problems/basic-calculator/discuss/62362/JAVA-Easy-Version-To-Understand!!!!!
public class Solution {
// 1-2-(4+5+2)-3
public int calculate(String s) {
int len = s.length(), sign = 1, result = 0;
// Use one stack for numbers, for operators used the sign, + -> 1, - -> -1
Stack<Integer> stack = new Stack<>();
for (int i = 0; i < len; i++) {
if (Character.isDigit(s.charAt(i))) {
int sum = s.charAt(i) - '0';
while (i + 1 < len && Character.isDigit(s.charAt(i + 1))) {
sum = sum * 10 + s.charAt(i + 1) - '0';
i++;
}
result += sum * sign;
} else if (s.charAt(i) == '+')
sign = 1;
else if (s.charAt(i) == '-')
sign = -1;
else if (s.charAt(i) == '(') {
stack.push(result);
stack.push(sign);
result = 0;
sign = 1;
} else if (s.charAt(i) == ')') {
// first pop is the sign, +1 or -1, second is the value
result = result * stack.pop() + stack.pop();
}
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment