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