day 28: 155-min-stack, 150-evaluate-reverse-polish-notation

This commit is contained in:
Kaushik Narayan R 2023-10-29 19:14:36 -07:00
parent ec5227eae8
commit 392b6c97e9
6 changed files with 121 additions and 0 deletions

View File

@ -0,0 +1,10 @@
#include "soln.hpp"
int main()
{
vector<string> tokens{"10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"};
int answer = 22;
Solution soln;
cout << "Evaluated postfix expression correctly? " << soln.test(tokens, answer) << endl;
return 0;
}

View File

@ -0,0 +1,42 @@
#include "soln.hpp"
int Solution::evalRPN(vector<string> &tokens)
{
vector<int> operands;
int a, b;
for (int i = 0; i < tokens.size(); i++)
{
if (tokens[i].length() > 1 || isdigit(tokens[i][0]))
{
operands.push_back(stoi(tokens[i]));
}
else
{
b = operands.back();
operands.pop_back();
a = operands.back();
operands.pop_back();
switch (tokens[i][0])
{
case '+':
operands.push_back(a + b);
break;
case '-':
operands.push_back(a - b);
break;
case '*':
operands.push_back(a * b);
break;
case '/':
operands.push_back(a / b);
break;
}
}
}
return operands[0];
}
bool Solution::test(vector<string> &tokens, int answer)
{
return evalRPN(tokens) == answer;
}

View File

@ -0,0 +1,8 @@
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
int evalRPN(vector<string> &tokens);
bool test(vector<string> &tokens, int answer);
};

14
155-min-stack/driver.cpp Normal file
View File

@ -0,0 +1,14 @@
#include "soln.hpp"
int main()
{
MinStack *minStack = new MinStack();
minStack->push(-2);
minStack->push(0);
minStack->push(-3);
cout << minStack->getMin() << endl; // return -3
minStack->pop();
cout << minStack->top() << endl; // return 0
cout << minStack->getMin() << endl; // return -2
return 0;
}

32
155-min-stack/soln.cpp Normal file
View File

@ -0,0 +1,32 @@
#include "soln.hpp"
MinStack::MinStack()
{
_stack = {};
total_min = INT_MAX;
}
void MinStack::push(int val)
{
total_min = min(int(val), total_min);
_stack.push_back({val, total_min});
}
void MinStack::pop()
{
_stack.pop_back();
if (_stack.size() == 0)
total_min = INT_MAX;
else
total_min = _stack.back().second;
}
int MinStack::top()
{
return int(_stack.back().first);
}
int MinStack::getMin()
{
return int(_stack.back().second);
}

15
155-min-stack/soln.hpp Normal file
View File

@ -0,0 +1,15 @@
#include <bits/stdc++.h>
using namespace std;
class MinStack
{
private:
vector<pair<int, int>> _stack;
int total_min;
public:
MinStack();
void push(int val);
void pop();
int top();
int getMin();
};