原题链接:227. Basic Calculator II
相似博文:224. Basic Calculator | Java最短代码实现
【思路】
本题考查字符串和数学运算的结合。有两种做法:第一种做法是第一遍先扫描乘除,第二遍扫描加减;第二种做法是将中间结果暂时压入栈中,遇到乘除,则从栈顶取出元素,再进行乘除运算,过后再压栈。本解法采用第二种做法:
public class Solution {
public int calculate(String s) {
Stack<Integer> stack = new Stack<Integer>();
int nums = 0, result = 0;
char sign = '+';
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (Character.isDigit(ch)) nums = nums*10 + ch-'0';
if ((ch == ' ' || Character.isDigit(ch)) && i < s.length()-1) continue;
if (sign == '+') stack.add(nums);
else if (sign == '-') stack.add(-nums);
else if (sign == '*') stack.add(stack.pop() * nums);
else if (sign == '/') stack.add(stack.pop() / nums);
sign = ch;
nums = 0;
}
while (!stack.isEmpty()) result += stack.pop();
return result;
}
}
109 / 109 test cases passed. Runtime: 35 ms Your runtime beats 70.59% of javasubmissions.
欢迎优化!