1,题目要求
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 "()()"
给定一个只包含字符’(‘和’)'的字符串,找到最长的有效(格式良好)括号子字符串的长度。
2,题目思路
对于这道题,要求求出匹配括号正确的最长字符串长度。
括号匹配问题我们已经很熟悉了,一个常规的办法是使用栈的方法来实现括号的匹配。
我们可以定义一个栈,栈内保存当前遍历的无法匹配的括号的索引。
因此,在这道题的解决上,首先,我们从头往后对给定的字符串进行搜索。
- 如果我们遇到’(’,我们就将它的索引加入到栈中;
- 如果我们遇到了’)’,而且栈非空,说明此时找到了一个配对,将此时栈顶的元素——即’(‘的索引——删除。
而遇到了’)’,而栈内又是空的,那么,我们就将’)'的索引加入到栈中。
当我们对字符串遍历完时,栈内存储的就是所有没有匹配成功的括号的下标索引。
- 如果栈是空的,说明所有的括号都是匹配的,那么,最长的字符匹配结果自然就是串长。
- 如果栈非空,那么,两个非匹配之间的括号一定是匹配的。那么,这两个索引的差就是当前的最长的匹配括号字符串长度。
3,代码实现
static const auto s = []() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
int longestValidParentheses(string s) {
int n = s.size(), res = 0;
stack<int> invalidIndex;
for(int i = 0;i<n;i++){
if(s[i] == '(')
invalidIndex.push(i);
else{ //s[i] == ')'
if(!invalidIndex.empty()){//当前栈非空
if(s[invalidIndex.top()] == '(') //找到匹配项
invalidIndex.pop();
else
invalidIndex.push(i);
}
else //当前栈内为空
invalidIndex.push(i);
}
}
//全部匹配,最长的结果就是串长
if(invalidIndex.empty())
res = n;
else{
int invalidRight = n, invalidLeft = 0;
while(!invalidIndex.empty()){
invalidLeft = invalidIndex.top();
invalidIndex.pop();
res = max(res, invalidRight-invalidLeft-1);
invalidRight = invalidLeft;
}
res = max(res, invalidRight);
}
return res;
}
};