-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path20_valid_parentheses.cpp
More file actions
36 lines (29 loc) · 888 Bytes
/
Copy path20_valid_parentheses.cpp
File metadata and controls
36 lines (29 loc) · 888 Bytes
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
#include <string>
#include <iostream>
#include <unordered_map>
#include <stack>
// O(N)
class Solution {
public:
bool isValid(const std::string& s) {
std::unordered_map<char, char> pair_p= {{'(', ')'}, {'{', '}'}, {'[', ']'}};
std::stack<char> open_p;
for (int i = 0; i < s.size(); i++){
char cur_p = s.at(i);
if (cur_p == '(' || cur_p == '{' || cur_p == '[')
open_p.push(cur_p);
else if (!open_p.empty() && cur_p == pair_p[open_p.top()])
open_p.pop();
else return false;
}
return open_p.empty();
}
};
int main(){
std::string s;
std::cout << "String with characters '(', ')', '{', '}': ";
std::cin >> s;
std::cout << std::boolalpha;
std::cout << "Is valid: " << Solution().isValid(s) << std::endl;
return 0;
}