#include <string>
#include <vector>
#include <iostream>
using namespace std;
/*
Given a string containing just the character '(' and ')', find the length of the longest
valid parentheses substring.
for "(()", the longest valid parentheses substring is "()" which has length 2.
Another example ")()())", where the longest valid parentheses substring is "()()", which
has length 4.
*/
// Use one pointer always points to the end index of vector.
int longestValidParentheses(string s) {
if(s.size() <= 1) return 0;
vector<int> index;
int maxSize = 0;
for(int i = 0; i < s.size(); ++i) {
if(s[i] == '(') {
index.push_back(i); // push the index number.
} else {
if(!index.empty() && s[index.back()] == '(') {
index.pop_back();
int lastPos = -1;
if(!index.empty()) {
lastPos = index.back();
}
maxSize = max(maxSize, i - lastPos);
} else {
index.push_back(i);
}
}
}
return maxSize;
}
int main(void) {
cout << longestValidParentheses("())()") << endl;
}
~ LeetCode 32. Longest Valid Parentheses
最新推荐文章于 2024-02-09 15:39:44 发布
本文介绍了一种使用栈的思想来解决寻找字符串中最长的有效括号子串的问题。通过遍历字符串并利用栈记录左括号的位置,可以高效地找出最长有效子串的长度。
319

被折叠的 条评论
为什么被折叠?



