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
Copy file name to clipboardExpand all lines: src/main/java/com/fishercoder/solutions/_224.java
+49
Original file line number
Diff line number
Diff line change
@@ -109,4 +109,53 @@ private int cal(String s) {
109
109
}
110
110
}
111
111
112
+
publicstaticclassSolution3 {
113
+
/**
114
+
* A more elegant solution using stack and iterative approach, credit: https://leetcode.com/problems/basic-calculator/solutions/62361/iterative-java-solution-with-stack/
115
+
* Key points:
116
+
* 1. use an integer to represent sign: 1 or -1, so it can be pushed onto a stack that's of Integer type;
117
+
*/
118
+
publicintcalculate(Strings) {
119
+
Deque<Integer> stack = newLinkedList<>();
120
+
intresult = 0;
121
+
intsign = 1;
122
+
intnum = 0;
123
+
for (inti = 0; i < s.length(); i++) {
124
+
charc = s.charAt(i);
125
+
if (Character.isDigit(c)) {
126
+
num = num * 10 + c - '0';
127
+
} elseif (c == '(') {
128
+
//we push the result onto the stack first, then sign
129
+
stack.addLast(result);
130
+
stack.addLast(sign);
131
+
132
+
//reset them
133
+
sign = 1;
134
+
num = 0;
135
+
} elseif (c == ')') {
136
+
//this means we reached the end of one parenthesis, so we compute result and reset num
137
+
result += num * sign;
138
+
num = 0;
139
+
140
+
result *= stack.pollLast();//this is the last sign we pushed onto the stack
141
+
result += stack.pollLast();//this is the last number on the stack
0 commit comments