This commit is contained in:
parent
91b8ac05f7
commit
955655bb0f
14
include/s0020_valid_parentheses.hpp
Normal file
14
include/s0020_valid_parentheses.hpp
Normal file
@ -0,0 +1,14 @@
|
||||
#ifndef S0020_VALID_PARENTHESES
|
||||
#define S0020_VALID_PARENTHESES
|
||||
|
||||
#include <stack>
|
||||
#include <string>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
bool isValid(string s);
|
||||
};
|
||||
|
||||
#endif
|
26
src/s0020_valid_parentheses.cpp
Normal file
26
src/s0020_valid_parentheses.cpp
Normal file
@ -0,0 +1,26 @@
|
||||
#include "s0020_valid_parentheses.hpp"
|
||||
|
||||
bool match(string s1, string s2) {
|
||||
return s1 == "(" && s2 == ")" ||
|
||||
s1 == "[" && s2 == "]" ||
|
||||
s1 == "{" && s2 == "}";
|
||||
}
|
||||
|
||||
// 直接用栈
|
||||
|
||||
bool Solution::isValid(string s) {
|
||||
stack<string> stack;
|
||||
int len = s.length();
|
||||
for (int i{0}; i < len; i++) {
|
||||
if (stack.empty()) {
|
||||
stack.push(s.substr(i, 1));
|
||||
} else {
|
||||
if (match(stack.top(), s.substr(i, 1))) {
|
||||
stack.pop();
|
||||
} else {
|
||||
stack.push(s.substr(i, 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
return stack.empty();
|
||||
}
|
31
tests/s0020_valid_parentheses.cpp
Normal file
31
tests/s0020_valid_parentheses.cpp
Normal file
@ -0,0 +1,31 @@
|
||||
#include "s0020_valid_parentheses.hpp"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
TEST(Problem20, Case1) {
|
||||
string i{"()"};
|
||||
bool o{true};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.isValid(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem20, Case2) {
|
||||
string i{"()[]{}"};
|
||||
bool o{true};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.isValid(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem20, Case3) {
|
||||
string i{"(]"};
|
||||
bool o{false};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.isValid(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem20, Case4) {
|
||||
string i{"(){}}{"};
|
||||
bool o{false};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.isValid(i), o);
|
||||
}
|
Loading…
Reference in New Issue
Block a user