No Sign C# using 2 Stacks


  • 0
    S
    public class Solution {
    public int Calculate(string s) {
        Stack<int> numst = new Stack<int>();
        Stack<char> opst = new Stack<char>();
        
        for(int i=0;i<s.Length;i++){
            if('0'<=s[i]&&'9'>=s[i]){
                int basenum=0;
                while(i<s.Length&&'0'<=s[i]&&'9'>=s[i]){
                    basenum = basenum*10+(s[i++]-'0');
                }
                if(opst.Count==0||opst.Peek()=='('){
                    numst.Push(basenum);
                }else{
                    int left = numst.Pop();
                    char op = opst.Pop();
                    if(op=='+'){
                        numst.Push(left+basenum);
                    }else{
                        numst.Push(left-basenum);
                    }
                }
                i--;
            }else if(s[i]=='('||s[i]=='+'||s[i]=='-'){
                opst.Push(s[i]);
            }else if(s[i]==')'){
                int right=numst.Pop();
                opst.Pop();
                if(opst.Count==0||opst.Peek()=='('){
                    numst.Push(right);
                }
                else{
                    int left = numst.Pop();
                    char op = opst.Pop();
                    if(op=='+'){
                        numst.Push(left+right);
                    }else{
                        numst.Push(left-right);
                    }
                }
            }
    
            
        }
    
        return numst.Peek();
    }
    

    }


Log in to reply
 

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