Skip to main content

Basic Calculator III

LeetCode Link

Problem Description​

Visit LeetCode for the full problem description.


Solutions​

Solution 1: C# (Best: 72 ms)​

MetricValue
Runtime72 ms
Memory37.1 MB
Date2022-01-25
Solution
public class Solution {
public int Calculate(string s) {
if(string.IsNullOrEmpty(s)) return 0;
Stack<int> st = new Stack<int>();
int current =0; char sign = '+';
int n = s.Length;
for (int i = 0; i < n; i++)
{
char c = s[i];
if
(char.IsDigit(c))
{
current = current*10 + (s[i]-'0');
}
else if(c == '(')
{
int j = i+1, braces = 1;
for(;j<n;j++)
{
if(s[j] == '(') ++braces;
if(s[j] == ')') --braces;
if(braces == 0) break;
}
current = Calculate(s.Substring(i+1,j-i));
i=j;
}

if(c == '+' || c == '-' || c == '*' || c == '/' || i == n-1)
{
if(sign == '+') st.Push(current);
if(sign == '-') st.Push(-current);
if(sign == '*') st.Push(st.Pop()*current);
if(sign=='/') st.Push(st.Pop()/current);
sign = c;
current = 0;
}
}

return st.Sum();
}
}

Complexity Analysis​

ApproachTimeSpace
SolutionTo be analyzedTo be analyzed