-
Notifications
You must be signed in to change notification settings - Fork 115
/
0772-BasicCalculatorIII.cs
72 lines (64 loc) · 2.17 KB
/
0772-BasicCalculatorIII.cs
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
//-----------------------------------------------------------------------------
// Runtime: 76ms
// Memory Usage: 24 MB
// Link: https://leetcode.com/submissions/detail/373281127/
//-----------------------------------------------------------------------------
using System.Collections.Generic;
namespace LeetCode
{
public class _0772_BasicCalculatorIII
{
public int Calculate(string s)
{
if (string.IsNullOrWhiteSpace(s)) return 0;
var stack = new Stack<int>();
int num = 0;
char sign = '+';
for (int i = 0; i < s.Length; i++)
{
var ch = s[i];
if (char.IsDigit(ch))
num = 10 * num + (ch - '0');
else if (ch == '(')
{
int balance = 1;
for (int j = i + 1; j < s.Length; j++)
{
if (s[j] == '(') balance++;
if (s[j] == ')') balance--;
if (balance == 0)
{
num = Calculate(s.Substring(i + 1, j - i - 1));
i = j;
break;
}
}
}
if (ch == '+' || ch == '-' || ch == '*' || ch == '/' || i == s.Length - 1)
{
switch (sign)
{
case '+':
stack.Push(num);
break;
case '-':
stack.Push(-num);
break;
case '*':
stack.Push(stack.Pop() * num);
break;
case '/':
stack.Push(stack.Pop() / num);
break;
}
num = 0;
sign = ch;
}
}
var result = 0;
while (stack.Count > 0)
result += stack.Pop();
return result;
}
}
}