s0032
This commit is contained in:
parent
ba6f75b394
commit
0a13bff07b
15
include/s0032_longest_valid_parentheses.hpp
Normal file
15
include/s0032_longest_valid_parentheses.hpp
Normal file
@ -0,0 +1,15 @@
|
||||
#ifndef S0032_LONGEST_VALID_PARENTHESES
|
||||
#define S0032_LONGEST_VALID_PARENTHESES
|
||||
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
using namespace std;
|
||||
|
||||
class Solution {
|
||||
public:
|
||||
int longestValidParentheses(string s);
|
||||
};
|
||||
|
||||
#endif
|
18
src/s0032_longest_valid_parentheses.cpp
Normal file
18
src/s0032_longest_valid_parentheses.cpp
Normal file
@ -0,0 +1,18 @@
|
||||
#include "s0032_longest_valid_parentheses.hpp"
|
||||
|
||||
int Solution::longestValidParentheses(string s) {
|
||||
int maxans = 0, n = s.length();
|
||||
vector<int> dp(n, 0);
|
||||
for (int i = 1; i < n; i++) {
|
||||
if (s[i] == ')') {
|
||||
if (s[i - 1] == '(') {
|
||||
dp[i] = (i >= 2 ? dp[i - 2] : 0) + 2;
|
||||
} else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') {
|
||||
dp[i] =
|
||||
dp[i - 1] + ((i - dp[i - 1]) >= 2 ? dp[i - dp[i - 1] - 2] : 0) + 2;
|
||||
}
|
||||
maxans = max(maxans, dp[i]);
|
||||
}
|
||||
}
|
||||
return maxans;
|
||||
}
|
31
tests/s0032_longest_valid_parentheses.cpp
Normal file
31
tests/s0032_longest_valid_parentheses.cpp
Normal file
@ -0,0 +1,31 @@
|
||||
#include "s0032_longest_valid_parentheses.hpp"
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
TEST(Problem32, Case1) {
|
||||
string i{"(()"};
|
||||
int o{2};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.longestValidParentheses(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem32, Case2) {
|
||||
string i{")()())"};
|
||||
int o{4};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.longestValidParentheses(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem32, Case3) {
|
||||
string i{"())"};
|
||||
int o{2};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.longestValidParentheses(i), o);
|
||||
}
|
||||
|
||||
TEST(Problem32, Case4) {
|
||||
string i{"()(()"};
|
||||
int o{2};
|
||||
Solution solution;
|
||||
EXPECT_EQ(solution.longestValidParentheses(i), o);
|
||||
}
|
Loading…
Reference in New Issue
Block a user