题目链接:
https://leetcode.com/problems/longest-valid-parentheses/description/
描述
Given a string containing just the characters ‘(’ and ‘)’, find the length of the longest valid (well-formed) parentheses substring.
For “(()”, the longest valid parentheses substring is “()”, which has length = 2.
Another example is “)()())”, where the longest valid parentheses substring is “()()”, which has length = 4.
输入
输入一个只有小括号的字符串。
输出
输出其连续匹配的最大长度。
样例输入
”)()())” “)()(()” |
样例输出
4 2 |
算法思想:
这道题使用了一个技巧,就是压栈压入的是字符串的小标,而不压入字母本身。当是左括号时,就压栈(压入的是其下表),如果是右括号且栈为空时,起始位置为当前的下标,否则,弹栈,之后再判断栈是否为空,后续操作。
源代码
class Solution {
public:
int S[100000];
int longestValidParentheses(string s) {
int len = s.length();
int sta = -1, cnt = 0, ans = 0, k = 0;
for (int i = 0; i < len; i++)
{
if (s[i] == '(')
{
S[k++] = i;
}
else
{
if (k == 0) sta = i;
else
{
k--;
if (k == 0) ans = max(ans, i - sta);
else
ans = max(ans,i - S[k - 1]);
}
}
}
return ans;
}
};