题目
leetcode 32
给定一个只包含 ‘(’ 和 ‘)’ 的字符串,找出最长的包含有效括号的子串的长度。
示例 1:
输入: “(()”
输出: 2
解释: 最长有效括号子串为 “()”
示例 2:
输入: “)()())”
输出: 4
解释: 最长有效括号子串为 “()()”
代码
int longestValidParentheses(char * s){
int count = 0, len, max = 0, top = -1, last = 0;
len = strlen(s);
int stack[len + 1], dp[len + 1];
//dp[]表示位置i有效括号长度
for (int i = 0; i < len; i++) {
dp[i] = 0;
}
int i = 0;
while (s[i] != '\0') {
if (s[i] == '(') {
stack[++top] = i;
} else if (top >= 0) {
count = i - stack[top] + 1;
if (stack[top] > 0) {
count += dp[stack[top] - 1];
}
top--;
dp[i] = count;
if (max < count) max = count;
}
i++;
}
return max;
}