[leetcode] Longest Valid Parentheses
程序员文章站
2024-03-01 10:20:04
...
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
Example 1:
Input: "(()"
Output: 2
Explanation: The longest valid parentheses substring is "()"
Example 2:
Input: ")()())"
Output: 4
Explanation: The longest valid parentheses substring is "()()"
Solution:
刚开始用的是的下面这个代码:
class Solution {
public:
int longestValidParentheses(string s) {
int count;
int sln = s.size();
int maxx = 0, maxright = 0;
for (int i=0, j; i<sln; ++i) {
count = 0;
for (j=i; j<sln; ++j) {
if (s[j] == '(') {
count++;
} else if(count > 0){
count--;
if(count == 0) {
maxright = j;
}
} else {
break;
}
}
if (maxx < maxright-i) {
maxx = maxright-i+1;
i = maxright;
}
}
return maxx;
}
};
后面发现其实可以在的时间内实现
class Solution {
public:
int longestValidParentheses(string s) {
stack<int> index_stack;
int sln = s.size(), maxx = 0, maxleft = 0;
for (int i=0, j; i<sln; ++i) {
if (s[i] == '(') {
index_stack.push(i);
} else if(index_stack.empty()) {
maxleft = i;
} else {
index_stack.pop();
if (index_stack.empty() && maxx < i - maxleft) {
maxx = i - maxleft;
} else if (maxx < i - index_stack.top()) {
maxx = i - index_stack.top();
}
}
}
return maxx;
}
};
推荐阅读
-
[leetcode] Longest Valid Parentheses
-
[LeetCode]3. Longest Substring Without Repeating Characters无重复字符的最长子串
-
【Leetcode】524. Longest Word in Dictionary through Deleting(最长子序列)
-
leetcode-5:Longest Palindromic Substring 最长回文子串
-
leetcode5:Longest Palindromic Substring最长回文子串
-
LeetCode 5. Longest Palindromic Substring(最长回文子串)
-
leetcode 5. Longest Palindromic Substring 回文串处理
-
【LeetCode】#5最长回文子串(Longest Palindromic Substring)
-
Leetcode 5. Longest Palindromic Substring 最长回文子串
-
leetcode 5st Longest Palindromic Substring