1️⃣.基本计数器(带括号)
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
class Solution {
public int calculate(String s) {
int len = s.length();
int sign = 1;
int res=0;
Deque<Integer> stack = new LinkedList();//stakc 存操作符号
stack.push(1);
int l=0;
while(l<len){
char c = s.charAt(l);
if(c==' '){
++l;
}else if(c=='+'){
sign = stack.peek();
++l;
}else if(c=='-'){
sign = -stack.peek();
++l;
}else if(c=='('){
stack.push(sign);
++l;
}else if(c==')'){
stack.pop();//** */
++l;
}else{
int num=0;
while(l<len&&Character.isDigit(s.charAt(l))){
num = 10*num+s.charAt(l)-'0';
++l;
}
res+=num*sign;//** */
}
}
return res;
}
}
2️⃣.基本计数器(带乘除)
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
class Solution {
//计算器-带乘除-栈存的是操作数
public int calculate(String s) {
int len = s.length();
int carr=0;
char sign ='+';
Deque<Integer> stack = new LinkedList();
for(int i=0;i<len;++i){
char c = s.charAt(i);
//遍历到的字符是数字
if(c>='0'){
carr =10*carr+c-'0';
}
//遍历到的字符是操作符号
if(c<'0'&&c!=' '||i==len-1){
if(sign=='+'){
stack.push(carr);
}else if(sign=='-'){
stack.push(-carr);
}else if(sign=='*'||sign=='/'){
int temp = sign=='*'?stack.pop()*carr:stack.pop()/carr;
stack.push(temp);
}
carr=0;
sign=c;
}
}
int res=0;
while(!stack.isEmpty()){
res+=stack.pop();
}
return res;
}
}
总结提炼🎯
1
1️⃣要舍得用指针