You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
classSolution {
publicintcalculate(Strings) {
if (s == null) {
return0;
}
Stack<Integer> stack = newStack<>();
intres = 0;
intsign = 1;
intnumber = 0;
for (inti = 0; i < s.length(); i++) {
Characterc = s.charAt(i);
if (c >= '0' && c <= '9') {
number = 10 * number + (c - '0');
}
elseif (c == '+') {
res += sign * number;
number = 0;
sign = 1;
}
elseif (c == '-') {
res += sign * number;
number = 0;
sign = -1;
}
elseif (c == '(') {
stack.push(res);
stack.push(sign);
number = 0;
sign = 1;
res = 0;
}
elseif (c == ')') {
res += sign * number;
res *= stack.pop();
res += stack.pop();
sign = 1;
number = 0;
}
}
if (number != 0) {
res += sign * number;
}
returnres;
}
}
note
The idea is to use a stack to store the sign & number and iterate through the string and evaluate accordingly in terms of the sign.
When it sees number, we update the number for future use (here, be careful the number might not be single digit, so we do
number * 10 + (c - 'a')).
When it sees '+' or '-', we will evaluate previous value and set number to 0 and sign accordingly.
When it sees '(', it means we need to store our previous result and sign temporarily and start evaluating expression in this
new parenthesis when we will push value first into stack and then sign (it's important that we push sign first so we can use
it later right after we finish evaluating the expression in this new parenthesis).
When it meets ')', we will first wrap up the calculation inside this parenthesis by res += sign * number and then pop out the sign and result before this parenthesis and update our value.
After the loop, check if number is 0. If not, we do a final calculation.
Solution2 (initial solution/brute force/slow)
classSolution {
publicintcalculate(Strings) {
Stack<Integer> stack = newStack<>();
s = s.trim();
intsign = 1;
for (inti = 0; i < s.length(); i++) {
charc = s.charAt(i);
if (c == '(') {
intcnt = -1;
intstart = i;
while (cnt != 0) {
i++;
if (s.charAt(i) == '(') {
cnt--;
}
if (s.charAt(i) == ')') {
cnt++;
}
}
stack.push(sign * calculate(s.substring(start + 1, i + 1)));
}
elseif (Character.isDigit(s.charAt(i))) {
intnum = 0;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
num = num * 10 + s.charAt(i) - '0';
i++;
}
i--;
stack.push(sign * num);
}
elseif (c == '+' || c == '-') {
sign = c == '+' ? 1 : -1;
System.out.println(sign);
}
}
intret = 0;
while (!stack.empty()) {
ret += stack.pop();
}
returnret;
}
}