32. Longest Valid Parentheses
原创
©著作权归作者所有:来自51CTO博客作者Shengjianjun的原创作品,请联系作者获取转载授权,否则将追究法律责任
题意:求出最长的正确括号匹配长度
思路:定义一个match数组,遍历s,每出现一个’)‘若前面有’('匹配,则match[idx]=i 若无匹配,则match[i]=-1;
最后遍历一次s,每次match[i]==-1或者match[i]0&&s[i]’('时断开 if语句和最后的条件运算符返回最大长度
int longestValidParentheses(string s) {
int match[100000];
memset(match, 0, sizeof(match));
int L_parentheses = 0;
int R_parentheses = 0;
for (int i = 0; i < s.length(); ++i) {
if (s[i] == '(')++L_parentheses;
else {
if (!L_parentheses) {
match[i] = -1;//means ) didnt match
continue;
}
int idx = i - 1;
while ((match[idx] !=0||s[idx]==')')&&idx>=0)--idx;
if (idx >= 0) {//found
match[idx] = i;//mark
}
--L_parentheses;
}
}
int max_Length = 0;
int temp_Length = 0;
for (int i = 0; i < s.length(); ++i) {
if (match[i] == -1 ||( match[i] == 0&&s[i]=='(')) {
if(temp_Length>max_Length)max_Length = temp_Length;
temp_Length = 0;
}
else ++temp_Length;
}
return max_Length>temp_Length?max_Length:temp_Length;
}
```