Basic Calculator III
Problem Descriptionβ
Visit LeetCode for the full problem description.
Solutionsβ
Solution 1: C# (Best: 72 ms)β
| Metric | Value |
|---|---|
| Runtime | 72 ms |
| Memory | 37.1 MB |
| Date | 2022-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β
| Approach | Time | Space |
|---|---|---|
| Solution | To be analyzed | To be analyzed |