C# solution using Stack


  • 0
    J
    public class Solution {
    public int Calculate(string s) {
        if(s==null||s.Length==0) { return 0; }
        int n=s.Length; Stack<int> nums=new Stack<int>(); Stack<char> ops=new Stack<char>(); int i=0;
        while(i<=n-1)
        {
            while(i<=n-1&&s[i]==' ') { i++; }
            if(i>n-1) { break; }
            if(s[i]>='0'&&s[i]<='9')
            {
                int j=i+1;
                while(j<=n-1&&s[j]>='0'&&s[j]<='9') { j++; }
                int v2=Convert.ToInt32(s.Substring(i,j-i)); nums.Push(v2);
                Cal_Impl(nums,ops);
                i=j;
            }
            else if(s[i]=='+'||s[i]=='-'||s[i]=='(')
            { ops.Push(s[i]); i++; }
            else if(s[i]==')')
            {
                ops.Pop();
                Cal_Impl(nums,ops);
                i++;
            }
        }
        return nums.Pop();
    }
    
    private void Cal_Impl(Stack<int> nums, Stack<char> ops)
    {
        if(ops.Count>0&&(ops.Peek()=='+'||ops.Peek()=='-'))
        {
            char op=ops.Pop();
            int v2=nums.Pop();
            int v1=nums.Pop();
            int v3=op=='+'? (v1+v2):(v1-v2);
            nums.Push(v3);
        }
    } }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.