Stack and DFS

Two Stacks

Implement a Queue

two-stack-queue

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
class MyQueue {
stack<int> input, output;
public:
/** Initialize your data structure here. */
MyQueue() {

}

/** Push element x to the back of queue. */
void push(int x) {
input.push(x);
}

/** Removes the element from in front of queue and returns that element. */
int pop() {
int tmp = peek();
output.pop();
return tmp;
}

/** Get the front element. */
int peek() {
if (output.empty())
while (input.size())
output.push(input.top()), input.pop();
return output.top();
}

/** Returns whether the queue is empty. */
bool empty() {
return input.empty() && output.empty();
}
};

Min Stack

min-stack

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class MinStack {
public:
void push(int x) {
stack.push(x);
if (small.empty() || small.top() >= x) small.push(x);
}

void pop() {
if (stack.top() == small.top()) small.pop();
stack.pop();
}

int top() {
return stack.top();
}

int getMin() {
return small.top();
}

private:
stack<int> stack;
stack<int> small;
};

Compare with Future

Compare with Next

Evaluate Reverse Polish Notation

1
2
3
Input: ["4", "13", "5", "/", "+"]
Output: 6
Explanation: (4 + (13 / 5)) = 6

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
int evalRPN(vector<string>& tokens) {
stack<int> S;
unordered_map<string, std::function<int(int,int)>> op;
op["+"] = [](int a, int b) { return a + b; };
op["-"] = [](int a, int b) { return a - b; };
op["*"] = [](int a, int b) { return a * b; };
op["/"] = [](int a, int b) { return a / b; };

for (auto t : tokens) {
if (op.find(t) != op.end()) {
int val2 = S.top(); S.pop();
int val1 = S.top(); S.pop();
int answ = op[t](val1, val2);
S.push(answ);
} else {
S.push(stoi(t));
}
}

return S.top();
}

Distance to Next Larger Cell in an Array

Daily Temperatures

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
vector<int> dailyTemperatures(vector<int>& T) {
stack<pair<int, int>> S;
vector<int> res(T.size());
if (T.empty()) return res;

for (int j = 0; j < T.size(); j++) {
while (!S.empty() && T[j] > S.top().first) {
res[S.top().second] = j - S.top().second;
S.pop();
}
S.push({ T[j], j });
}

while (!S.empty()) {
res[S.top().second] = 0;
S.pop();
}

return res;
}

Match with Next Valid Cell in an Array

Valid Parentheses

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool isValid(string s) {
stack<char> S;
unordered_map<char, bool> is_left;
is_left['('] = true;
is_left['['] = true;
is_left['{'] = true;

unordered_map<char, char> to_left;
to_left['}'] = '{';
to_left[']'] = '[';
to_left[')'] = '(';

for (auto c : s)
{
if (is_left[c]) S.push(c);
else if (S.empty() || S.top() != to_left[c]) return false;
else S.pop();
}

return S.empty();
}

Decode String

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
string decodeString(string s) {
string res;
stack<pair<char, int>> S;
for (int i = 0; i < s.length(); i++) {
if (isalpha(s[i])) {
res.push_back(s[i]);
} else {
if (s[i] == ']') {
size_t start = S.top().second; S.pop();
string substr = res.substr(start, res.size() - start);

string num;
while (!S.empty() && S.top().first != '[') {
num += S.top().first; S.pop();
}
reverse(num.begin(), num.end());
int times = stoi(num);

for (int k = 0; k < times - 1; k++)
res += substr;
} else {
S.push({s[i], res.size()});
}
}
}
return res;
}