add: 220524 [cpp]

This commit is contained in:
Eat-Swap 2022-05-24 21:20:20 +08:00
parent 26d14ac79c
commit 02bf5f38a3
Signed by: Eatswap
GPG Key ID: BE661106A1F3FA0B
2 changed files with 33 additions and 1 deletions

32
cpp/2205/220524.cpp Normal file
View File

@ -0,0 +1,32 @@
#include <stack>
#include <string>
#include <iostream>
/**
* 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<int16_t> 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;
}

View File

@ -3,4 +3,4 @@ PROJECT(2205)
SET(CMAKE_CXX_STANDARD 23)
ADD_EXECUTABLE(2205 220524-CN.cpp)
ADD_EXECUTABLE(2205 220524.cpp)