-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalid_parentheses.cpp
More file actions
40 lines (37 loc) · 960 Bytes
/
valid_parentheses.cpp
File metadata and controls
40 lines (37 loc) · 960 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
37
38
39
40
// 20. Valid Parentheses: https://leetcode.com/problems/valid-parentheses
// Author: xianfeng.zhu@gmail.com
#include <stack>
#include <string>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
class Solution {
public:
bool isValid(const std::string& s) {
std::stack<char> chrs;
for (const auto c : s) {
if (c == '(') {
chrs.push(')');
} else if (c == '[') {
chrs.push(']');
} else if (c == '{') {
chrs.push('}');
} else if (!chrs.empty() && chrs.top() == c) {
chrs.pop();
} else {
return false;
}
}
return chrs.empty();
}
};
TEST(Solution, isValud) {
std::vector<std::pair<std::string, bool>> cases = {
std::make_pair(std::string("()"), true),
std::make_pair(std::string("()[]{}"), true),
std::make_pair(std::string("(]"), false),
};
for (auto& c : cases) {
EXPECT_EQ(Solution().isValid(c.first), c.second);
}
}