My accepted C# O(n) Solution


  • 0
    S

    Use Stack to store all the numbers, use switch to operate the numbers.

    here's the code:
    public class Solution {
    public int EvalRPN(string[] tokens) {
    bool isNum;
    Stack<int> numStack= new Stack<int>();// store the numbers in a stack
    int OpdCount=0;
    String temp="";
    for(int i=0; i< tokens.Length; i++)
    {
    int num;
    isNum=int.TryParse(tokens[i], out num);//check if it is a number
    if(isNum)// if it is a number, push it into the stack
    {
    numStack.Push(num);
    temp +=tokens[i];
    }
    else // if it's not a number, then pop out the last 2 numbers in stack and operater
    {
    OpdCount++;
    int top1= numStack.Pop();
    int top2= numStack.Pop();
    numStack.Push(operateNums(top2, top1, tokens[i]));
    }

        }
        
        if(OpdCount>0)
        {
            return numStack.Pop();
        }
        else
        {
            int n;
            int.TryParse(temp, out n);
            return n;
        }
    }
    
    public int operateNums(int a, int b, string opd)
    {
        int result=0;
        switch (opd)
        {
            case "+" : result=a+b; 
                break;
            case "-" : result=a-b; 
                break; 
            case "/" : result=a/b; 
                break;
            case "*" : result=a*b; 
                break;
        }
        return result;
    }
    

    }


Log in to reply
 

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