难度:Hard
描述:
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.
思路:之前做了个生成有效的括号串的题,最开始想用左右括号的数量关系来解决,想了半天,没效果,因为光凭数量关系是很难区分有效子串是否连在一起,放弃了。
之后决定使用这个方法:把不符合规则的字符替换为空格,这样就能得出,一堆子串,再比较他们长度就行。
那怎么做到呢?可以使用栈来实现,对于左括号,将其index入栈,遇到右括号,就出栈,当栈空时遇到右括号,可以直接判断这个右括号是无效的。
最终栈中剩下的index,则是无效左括号的index,将它们全部赋值为空格。
最后扫描整个字符串,得出最长有效子串,完成。
代码:
#include <vector>
class Solution {
public:
int longestValidParentheses(string s) {
std::vector<int> wl; //use vector as a stack
int l = 0;
for (int i = 0; i < s.size(); i++){
if (s[i] == ')' && l == 0){
s[i] = ' ';
} else if (s[i] == ')' && l != 0){
wl.pop_back();
l--;
} else if (s[i] == '('){
wl.push_back(i);
l++;
}
}
for (int i = 0; i < wl.size(); i++){
s[wl[i]] = ' ';
}
int max = 0;
int temp = 0;
for (int i = 0; i < s.size(); i++){
if (s[i] != ' '){
temp++;
} else {
if (temp > max) max = temp;
temp = 0;
}
}
if (temp > max) return temp;
else return max;
}
};