|
| 1 | +using System; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Linq; |
| 4 | +using System.Text; |
| 5 | +using Microsoft.VisualBasic.CompilerServices; |
| 6 | + |
| 7 | +namespace LeetCodeSolutionsLib |
| 8 | +{ |
| 9 | + /// <summary> |
| 10 | + /// 150. Evaluate Reverse Polish Notation |
| 11 | + /// Evaluate the value of an arithmetic expression in Reverse Polish Notation |
| 12 | + /// Valid Operators are + - * / |
| 13 | + /// IE) Input : ["2", "1", "+", "3", "*"] |
| 14 | + /// Output : 9 |
| 15 | + /// Explanation: ((2 + 1) * 3) = 9 |
| 16 | + /// </summary> |
| 17 | + public class EvaluateReversePolishNotation : Solution |
| 18 | + { |
| 19 | + private string[] _inputString; |
| 20 | + |
| 21 | + public EvaluateReversePolishNotation(string[] tokens) |
| 22 | + { |
| 23 | + this._inputString = tokens; |
| 24 | + } |
| 25 | + |
| 26 | + private int evaluateReversePolishNotation(string[] tokens) |
| 27 | + { |
| 28 | + // Using a Stack, loop through each string in 'tokens' array |
| 29 | + // 1) If element is a number, push it on top the stack |
| 30 | + // 2) If element is an operator, pop two numbers from the stack, do the correct calculations and push back the results. |
| 31 | + // Time Complexity : O(n) where n is the size of the token's array |
| 32 | + // Space Complexity: O(n) |
| 33 | + string validOperators = "+-*/"; |
| 34 | + Stack<int> stack = new Stack<int>(); |
| 35 | + int number = 0; |
| 36 | + foreach (var element in tokens) |
| 37 | + { |
| 38 | + // 1) |
| 39 | + if (int.TryParse(element, out number)) |
| 40 | + { |
| 41 | + stack.Push(number); |
| 42 | + } |
| 43 | + // 2) |
| 44 | + else |
| 45 | + { |
| 46 | + int rightValue = stack.Pop(); |
| 47 | + int leftValue = stack.Pop(); |
| 48 | + int operatorIndex = validOperators.IndexOf(element); |
| 49 | + // Console.WriteLine($"{leftValue} {element.ToString()} {rightValue}"); |
| 50 | + switch (operatorIndex) |
| 51 | + { |
| 52 | + case 0: |
| 53 | + stack.Push(leftValue + rightValue); |
| 54 | + break; |
| 55 | + case 1: |
| 56 | + stack.Push(leftValue - rightValue); |
| 57 | + break; |
| 58 | + case 2: |
| 59 | + stack.Push(leftValue * rightValue); |
| 60 | + break; |
| 61 | + case 3: |
| 62 | + stack.Push(leftValue / rightValue); |
| 63 | + break; |
| 64 | + } |
| 65 | + } |
| 66 | + } |
| 67 | + return stack.Pop(); |
| 68 | + } |
| 69 | + public override void PrintExample() |
| 70 | + { |
| 71 | + var watch = System.Diagnostics.Stopwatch.StartNew(); |
| 72 | + var results = evaluateReversePolishNotation(this._inputString); |
| 73 | + watch.Stop(); |
| 74 | + Console.WriteLine($"150. Evaluate Reverse Polish Notation\n" + |
| 75 | + $"Input String = {printInputArray(this._inputString)} \n" + |
| 76 | + $"Result: [{results}] \n" + |
| 77 | + $"Execution Speed: {watch.ElapsedMilliseconds}ms \n"); |
| 78 | + } |
| 79 | + } |
| 80 | +} |
0 commit comments