forked from fishercoder1534/Leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_224.java
74 lines (69 loc) · 2.97 KB
/
_224.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.fishercoder.solutions;
import java.util.Deque;
import java.util.LinkedList;
public class _224 {
public static class Solution1 {
/**
* My complete original solution on 12/23/2021
*/
public int calculate(String s) {
Deque<String> stack = new LinkedList<>();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == ' ') {
continue;
} else {
if (s.charAt(i) == '(' || s.charAt(i) == '+' || s.charAt(i) == '-') {
stack.addLast(s.charAt(i) + "");
} else if (Character.isDigit(s.charAt(i))) {
int start = i;
while (i < s.length() && Character.isDigit(s.charAt(i))) {
i++;
}
stack.addLast(s.substring(start, i));
i--;
} else if (s.charAt(i) == ')') {
int result = 0;
while (!stack.isEmpty() && !stack.peekLast().equals("(")) {
String numStr = stack.pollLast();
int numInt = Integer.parseInt(numStr);
if (!stack.isEmpty() && (stack.peekLast().equals("-") || stack.peekLast().equals("+"))) {
String operator = stack.pollLast();
if (operator.equals("+")) {
result += numInt;
} else if (operator.equals("-")) {
result -= numInt;
}
} else {
result += numInt;
if (!stack.isEmpty() && stack.peekLast().equals("(")) {
stack.pollLast();
break;
}
}
}
if (!stack.isEmpty() && stack.peekLast().equals("(")) {
stack.pollLast();
}
stack.addLast(result + "");
}
}
}
int result = 0;
while (!stack.isEmpty() && stack.peekLast() != "(") {
String numStr = stack.pollLast();
int numInt = Integer.parseInt(numStr);
if (!stack.isEmpty()) {
String operator = stack.pollLast();
if (operator.equals("+")) {
result += numInt;
} else if (operator.equals("-")) {
result -= numInt;
}
} else {
result += numInt;
}
}
return !stack.isEmpty() ? Integer.parseInt(stack.peekLast()) + result : result;
}
}
}