-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathValidParentheses.h
50 lines (40 loc) · 1.21 KB
/
ValidParentheses.h
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
//
// Created by cameron on 12/6/21.
//
#pragma once
#include <unordered_map>
#include <stack>
#include "CodeChallenge.h"
class ValidParentheses : public CodeChallenge {
public:
void runChallenge() override {
std::string test1 = "()"; // true
std::string test2 = "()[]{}"; // true
std::string test3 = "]"; // false
std::string test4 = "{[]}"; // true
std::cout << std::boolalpha << isValid(test1) << std::endl;
std::cout << std::boolalpha << isValid(test2) << std::endl;
std::cout << std::boolalpha << isValid(test3) << std::endl;
std::cout << std::boolalpha << isValid(test4) << std::endl;
}
static bool isValid(const std::string& s) {
std::stack<char> stack;
std::unordered_map<char, char> map = {
{')', '('},
{']', '['},
{'}', '{'},
};
for (const auto& c: s) {
if (map.find(c) != map.end()) {
if (stack.empty() || stack.top() != map[c]) {
return false;
}
stack.pop();
}
else {
stack.push(c);
}
}
return stack.empty();
}
};