0%

leetCode-227:Basic Calculator II

问题描述

给定一个字符串表达式,只包含数字、空格和 +-*/,已知这个表达式合法,且不会出现负数,对于除法,向下取整,即 3 / 2 = 1。要求求出这个表达式的值。题目链接:**点我**

样例输入输出

输入:5 / 2

输出:2

输入:4 + 3 *2

输出:10

问题解法

针对表达式求值,将中缀表达式转成后缀表达式,然后运用栈进行求解。针对此题,只包含加减乘除,并没有括号,相比而言会简单点。代码如下

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
class Solution
{
public int calculate(String s)
{
Stack<Character> opStack = new Stack<>();
Stack<Integer> numStack = new Stack<>();
int num = 0;
boolean isAdd = false;
for (int i = 0; i < s.length(); i++)
{
char ch = s.charAt(i);
if (Character.isDigit(ch))
{
num = num * 10 + (ch - '0');
isAdd = true;
continue;
}

if (isAdd)
{
numStack.push(num);
num = 0;
isAdd = false;
}

if (ch == ' ')
{
continue;
}

while (!opStack.isEmpty() && !isHigh(ch, opStack.peek()))
{
int second = numStack.pop();
int first = numStack.pop();
numStack.push(calc(first, second, opStack.pop()));
}

opStack.push(ch);
}

if (isAdd)
{
numStack.push(num);
}

while (!opStack.isEmpty())
{
int second = numStack.pop();
int first = numStack.pop();
numStack.push(calc(first, second, opStack.pop()));
}

return numStack.pop();
}

private int calc(int first, int second, char op)
{
if (op == '+')
{
return first + second;
}

if (op == '-')
{
return first - second;
}

if (op == '*')
{
return first * second;
}

return first / second;
}

private boolean isHigh(char first, char second)
{
return (first == '*' || first == '/') && (second == '+' || second == '-');
}
}