Skip to content

Commit c732843

Browse files
committedNov 20, 2022
leetcode
1 parent 7479b37 commit c732843

File tree

4 files changed

+456
-0
lines changed

4 files changed

+456
-0
lines changed
 

‎BasicCalculator/basic_calculator.dart

+243
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,243 @@
1+
/*
2+
3+
-* 224. Basic Calculator *-
4+
5+
Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.
6+
7+
Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().
8+
9+
10+
11+
Example 1:
12+
13+
Input: s = "1 + 1"
14+
Output: 2
15+
Example 2:
16+
17+
Input: s = " 2-1 + 2 "
18+
Output: 3
19+
Example 3:
20+
21+
Input: s = "(1+(4+5+2)-3)+(6+8)"
22+
Output: 23
23+
24+
25+
Constraints:
26+
27+
1 <= s.length <= 3 * 105
28+
s consists of digits, '+', '-', '(', ')', and ' '.
29+
s represents a valid expression.
30+
'+' is not used as a unary operation (i.e., "+1" and "+(2 + 3)" is invalid).
31+
'-' could be used as a unary operation (i.e., "-1" and "-(2 + 3)" is valid).
32+
There will be no two consecutive operators in the input.
33+
Every number and running calculation will fit in a signed 32-bit integer.
34+
35+
*/
36+
import 'dart:collection';
37+
38+
class A {
39+
int calculate(String s) {
40+
int sign = 1;
41+
int result = 0;
42+
int number = 0;
43+
44+
int n = s.length;
45+
List<int> st = [];
46+
47+
for (int i = 0; i < n; i++) {
48+
String c = s[i];
49+
if (c.codeUnitAt(0) >= '0'.codeUnitAt(0) &&
50+
c.codeUnitAt(0) <= '9'.codeUnitAt(0)) {
51+
number = number * 10 + (c.codeUnitAt(0) - '0'.codeUnitAt(0));
52+
}
53+
if (c == '-') {
54+
// number completed.
55+
// update result
56+
result += (sign) * (number);
57+
number = 0;
58+
sign = -1;
59+
}
60+
if (c == '+') {
61+
// number completed
62+
// update result
63+
result += (sign) * (number);
64+
number = 0;
65+
sign = 1;
66+
}
67+
if (c == '(') {
68+
// number completed, result updated already before when we encountered +/- before opening bracket
69+
st.add(result);
70+
// so that sign remains at the top (signifies sign before opening bracket was encountered)
71+
st.add(sign);
72+
result = 0; // building result between brackets from scratch
73+
sign = 1;
74+
}
75+
if (c == ')') {
76+
// number is completed
77+
// update result
78+
result += (sign) * (number);
79+
number = 0;
80+
result *= st.first; // multiplying with sign before opening bracket
81+
st.removeLast();
82+
result += st.first; // result constructed before current context.
83+
st.removeLast();
84+
}
85+
}
86+
87+
// last no space character in case is a number itself , we need to use the number also.
88+
result += (sign) * number;
89+
90+
return result;
91+
}
92+
}
93+
94+
class B {
95+
bool isDigit(String? s) {
96+
if (s == null) {
97+
return false;
98+
}
99+
return int.tryParse(s) != null;
100+
}
101+
102+
int calculate(String s) {
103+
List<int> stack = [];
104+
int result = 0;
105+
int number = 0;
106+
int sign = 1;
107+
for (int i = 0; i < s.length; i++) {
108+
String c = s[i];
109+
if (isDigit(c)) {
110+
number = 10 * number + (c.codeUnitAt(0) - '0'.codeUnitAt(0));
111+
} else if (c == '+') {
112+
result += sign * number;
113+
number = 0;
114+
sign = 1;
115+
} else if (c == '-') {
116+
result += sign * number;
117+
number = 0;
118+
sign = -1;
119+
} else if (c == '(') {
120+
//we push the result first, then sign;
121+
stack.add(result);
122+
stack.add(sign);
123+
//reset the sign and result for the value in the parenthesis
124+
sign = 1;
125+
result = 0;
126+
} else if (c == ')') {
127+
result += sign * number;
128+
number = 0;
129+
result *=
130+
stack.removeLast(); //stack.pop() is the sign before the parenthesis
131+
result += stack
132+
.removeLast(); //stack.pop() now is the result calculated before the parenthesis
133+
134+
}
135+
}
136+
if (number != 0) result += sign * number;
137+
return result;
138+
}
139+
}
140+
141+
class C {
142+
bool isDigit(String? s) {
143+
if (s == null) {
144+
return false;
145+
}
146+
return int.tryParse(s) != null;
147+
}
148+
149+
int calculate(String s) {
150+
// all possible case: "+", "-", "(", ")", " ", "1-9"
151+
// +: change sign to positive +1
152+
// -: change sign to negative -1
153+
// (: push current result value and sign onto the stack
154+
// ): pop the previous result value and sign off the stack and do the addition
155+
// " ": skip
156+
// 1-9: read all digits after current digit
157+
Queue<int> stack = Queue();
158+
// initialize result to be 0, sign to be 1
159+
int res = 0, sign = 1;
160+
161+
int n = s.length;
162+
// iterate through all characters of the input
163+
for (int i = 0; i < n; i++) {
164+
String curr = s[i];
165+
switch (curr) {
166+
case '+':
167+
// make sign become positive to indicate we are adding a value
168+
sign = 1;
169+
break;
170+
case '-':
171+
// make sign become negative to indicate we are subtracting a value
172+
sign = -1;
173+
break;
174+
case '(':
175+
// pushing current result as well as the sign onto the stack
176+
stack.addFirst(res);
177+
stack.addFirst(sign);
178+
// reset result and sign
179+
res = 0;
180+
sign = 1;
181+
break;
182+
case ')':
183+
// popping previous result and sign off the stack and do the addition(subtraction)
184+
// with the current calculation result
185+
int prevSign = stack.removeFirst();
186+
int prevRes = stack.removeFirst();
187+
res = prevRes + prevSign * res;
188+
break;
189+
case ' ':
190+
// skip the empty spaces
191+
break;
192+
default:
193+
// in case current char is a digit, read the whole integer
194+
int startIdx = i;
195+
while (i < n && isDigit(s[i])) {
196+
i++;
197+
}
198+
int v = int.parse(s.substring(startIdx, i));
199+
res += sign * v;
200+
i--;
201+
}
202+
}
203+
return res;
204+
}
205+
}
206+
207+
class D {
208+
int pos = 0;
209+
bool isNum(String curr) {
210+
int nums = curr.codeUnitAt(0) - '0'.codeUnitAt(0);
211+
return nums >= 0 && nums <= 9;
212+
}
213+
214+
int solve(String s) {
215+
int sign = 1; // initial take as positive
216+
int nums = 0;
217+
int res = 0;
218+
while (pos < s.length) {
219+
String curr = s[pos++];
220+
if (curr == ' ') {
221+
continue;
222+
} else if (isNum(curr)) {
223+
nums = nums * 10 + curr.codeUnitAt(0) - '0'.codeUnitAt(0);
224+
} else if (curr == '(') {
225+
nums = solve(s);
226+
} else if (curr == ')') {
227+
res += nums * sign;
228+
return res;
229+
} else {
230+
res += sign * nums;
231+
sign = curr == '-' ? -1 : 1;
232+
nums = 0;
233+
}
234+
}
235+
int ret = res + (sign * nums);
236+
return ret;
237+
}
238+
239+
int calculate(String s) {
240+
pos = 0;
241+
return solve(s);
242+
}
243+
}

‎BasicCalculator/basic_calculator.go

+41
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
package main
2+
3+
import "strings"
4+
5+
func calculate(s string) int {
6+
// for easier code, remove all blank and append a ")"
7+
s = strings.ReplaceAll(s, " ", "") + ")"
8+
result, _ := calcUntilBrackets(s, 0)
9+
return result
10+
}
11+
12+
// return calc result and endIndex
13+
func calcUntilBrackets(s string, startIndex int) (int, int) {
14+
calcResult := 0
15+
current := 0
16+
sign := 1
17+
for i := startIndex; i < len(s); i++ {
18+
v := s[i]
19+
if v >= '0' && v <= '9' {
20+
current = current*10 + int(v-'0')
21+
continue
22+
}
23+
24+
calcResult += current * sign
25+
current = 0
26+
27+
if v == '(' {
28+
inner, bracket := calcUntilBrackets(s, i+1)
29+
i = bracket
30+
calcResult += inner * sign
31+
} else if v == ')' {
32+
return calcResult, i
33+
} else if v == '+' {
34+
sign = 1
35+
} else if v == '-' {
36+
sign = -1
37+
}
38+
}
39+
// code reach here is impossible
40+
return calcResult, -1
41+
}

0 commit comments

Comments
 (0)