class Solution {
public:
int longestValidParentheses(string s) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
int maxLength = 0;
vector<int> fastest(s.size() + 1, -1); //fastest[i]表示和i处'('匹配的')'的位置
s += '('; //哨兵
for (int i = s.size() - 1; i >= 0; --i)
{
if (s[i] == '(')
{
int j = i + 1;
while (s[j] == '(' && fastest[j] != -1)
{
j = fastest[j] + 1;
}
fastest[i] = s[j] == ')' ? j : -1;
}
}
int curLength = 0;
for (int i = 0; i < fastest.size();) //计算最大匹配括号长度
{
if (fastest[i] == -1)
{
maxLength = max(maxLength, curLength);
curLength = 0;
++i;
}
else
{
curLength += fastest[i] - i + 1;
i = fastest[i] + 1;
}
}
return maxLength;
}
};
LeetCode-Longest Valid Parentheses
最新推荐文章于 2024-07-15 11:08:21 发布