问题:
难度:medium
说明:
简单算术运算,就是写一个可以编译 + - * / 四则运算的简单程序,将输入的字符串解析并得到结果,其中把空格去掉就行。
题目连接:https://leetcode.com/problems/basic-calculator-ii/
相关算法:
[编译原理随记]简单的中序转后缀算术翻译器 ii:https://blog.csdn.net/qq_28033719/article/details/106940231
输入案例:
Example 1:
Input: "3+2*2"
Output: 7
Example 2:
Input: " 3/2 "
Output: 1
Example 3:
Input: " 3+5 / 2 "
Output: 5
我的代码:
其实这个就跟自动机差不多,直接当算法做也不会太难,也不用写得跟自动机一样多步骤。
class Solution {
private int index = 0;
private static int tens = 10;
public int calculate(String s) {
char[] chs = s.toCharArray();
int len = s.length(), total = match(len, chs);
while(index < len) {
char c = chs[index ++];
switch(c) {
case '+' : total += match(len, chs); break;
case '-' : total -= match(len, chs); break;
}
}
return total;
}
public int match(int len, char[] chs) { // 匹配符号
int num = 0;
A:for(; index < len;) {
char c = chs[index];
switch(c) {
case ' ' : index ++; continue;
case '+' : case '-' : break A;
case '*' : index ++; num *= match2(len, chs); break;
case '/' : index ++; num /= match2(len, chs); break;
default : num = num * tens + (c - '0'); index ++;
}
}
return num;
}
public int match2(int len, char[] chs) { // 重复写了一个,给 * / 用
int num = 0;
A:for(; index < len; index ++) {
char c = chs[index];
switch(c) {
case ' ' : continue;
case '+' : case '-' : case '*' : case '/' : break A;
default : num = num * tens + (c - '0');
}
}
return num;
}
}