From 0a13bff07bfed219552709dd7ff59bb9d2fcd045 Mon Sep 17 00:00:00 2001 From: Sainnhe Park Date: Mon, 21 Nov 2022 16:51:23 +0800 Subject: [PATCH] s0032 --- include/s0032_longest_valid_parentheses.hpp | 15 ++++++++++ src/s0032_longest_valid_parentheses.cpp | 18 ++++++++++++ tests/s0032_longest_valid_parentheses.cpp | 31 +++++++++++++++++++++ 3 files changed, 64 insertions(+) create mode 100644 include/s0032_longest_valid_parentheses.hpp create mode 100644 src/s0032_longest_valid_parentheses.cpp create mode 100644 tests/s0032_longest_valid_parentheses.cpp diff --git a/include/s0032_longest_valid_parentheses.hpp b/include/s0032_longest_valid_parentheses.hpp new file mode 100644 index 0000000..8aef8f7 --- /dev/null +++ b/include/s0032_longest_valid_parentheses.hpp @@ -0,0 +1,15 @@ +#ifndef S0032_LONGEST_VALID_PARENTHESES +#define S0032_LONGEST_VALID_PARENTHESES + +#include +#include +#include + +using namespace std; + +class Solution { + public: + int longestValidParentheses(string s); +}; + +#endif diff --git a/src/s0032_longest_valid_parentheses.cpp b/src/s0032_longest_valid_parentheses.cpp new file mode 100644 index 0000000..c146389 --- /dev/null +++ b/src/s0032_longest_valid_parentheses.cpp @@ -0,0 +1,18 @@ +#include "s0032_longest_valid_parentheses.hpp" + +int Solution::longestValidParentheses(string s) { + int maxans = 0, n = s.length(); + vector 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; +} diff --git a/tests/s0032_longest_valid_parentheses.cpp b/tests/s0032_longest_valid_parentheses.cpp new file mode 100644 index 0000000..49ee0b6 --- /dev/null +++ b/tests/s0032_longest_valid_parentheses.cpp @@ -0,0 +1,31 @@ +#include "s0032_longest_valid_parentheses.hpp" + +#include + +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); +}