Clean C# solution


  • 0
    J

    Straight forward solution using stack.
    Time Complexity: O(N)
    Space: O(N)

        public int EvalRPN(string[] t)
        {
            var s = new Stack<string>();
            foreach (var o in t)
            {
                if (o == "+" || o == "-" || o == "*" || o == "/")
                {
                    c(s, o);
                }
                else
                {
                    s.Push(o);
                }
            }
    
            return int.Parse(s.Pop());
        }
    
        void c(Stack<string> s, string o)
        {
            int a = int.Parse(s.Pop());
            int b= int.Parse(s.Pop());
    
            switch (o)
            {
                case "+":
                    s.Push(b + a + "");
                    break;
                case "-":
                    s.Push(b - a + "");
                    break;
                case "*":
                    s.Push(b * a + "");
                    break;
                case "/":
                    s.Push(b / a + "");
                    break;
                default:
                    break;
            }
        }

Log in to reply
 

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