From 02bf5f38a391c7983cc78d64cf74e4ae6fca44ea Mon Sep 17 00:00:00 2001 From: Eat-Swap Date: Tue, 24 May 2022 21:20:20 +0800 Subject: [PATCH] add: 220524 [cpp] --- cpp/2205/220524.cpp | 32 ++++++++++++++++++++++++++++++++ cpp/2205/CMakeLists.txt | 2 +- 2 files changed, 33 insertions(+), 1 deletion(-) create mode 100644 cpp/2205/220524.cpp diff --git a/cpp/2205/220524.cpp b/cpp/2205/220524.cpp new file mode 100644 index 0000000..d475b7a --- /dev/null +++ b/cpp/2205/220524.cpp @@ -0,0 +1,32 @@ +#include +#include +#include + +/** + * 32. Longest Valid Parentheses + * Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring. + */ + +class Solution { +public: + static int longestValidParentheses(const std::string& s) { + std::stack stack; + int16_t last_success = -1; + const int16_t len = s.length(); + + int ans = 0; + for (int16_t i = 0; i < len; ++i) + if ('(' == s[i]) + stack.push(i); + else if (stack.empty()) + last_success = i; + else + ans = std::max(ans, i - ((stack.pop(), stack.empty()) ? last_success : stack.top())); + return ans; + } +}; + +int main() { + std::cout << Solution::longestValidParentheses(")()(((()()()))))()()()"); + return 0; +} diff --git a/cpp/2205/CMakeLists.txt b/cpp/2205/CMakeLists.txt index 0ca418f..d441493 100644 --- a/cpp/2205/CMakeLists.txt +++ b/cpp/2205/CMakeLists.txt @@ -3,4 +3,4 @@ PROJECT(2205) SET(CMAKE_CXX_STANDARD 23) -ADD_EXECUTABLE(2205 220524-CN.cpp) +ADD_EXECUTABLE(2205 220524.cpp)