forked from lolosssss/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path32_longest_valid_parentheses.c
58 lines (48 loc) · 1.4 KB
/
32_longest_valid_parentheses.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/**
* Description : Longest Valid Parentheses
* 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.
* Author : Evan Lau
* Date : 2016/03/20
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int longestValidParentheses(char* s)
{
int len = strlen(s);
int max = 0;
int *stack = (int *)malloc(sizeof(int) * len);
if (len < 2)
return 0;
memset(stack, 0, sizeof(int) * len);
for (int i = 1; i < len; i++)
{
if (s[i] == ')')
{
if (s[i - 1] == '(')
{
stack[i] = 2 + (i > 1 ? stack[i - 2] : 0);
}
else if (i - stack[i - 1] > 0 && s[i - stack[i - 1] - 1] == '(')
{
stack[i] = stack[i - 1] + stack[i - stack[i - 1] - 2] + 2;
}
if (stack[i] > max)
max = stack[i];
}
}
return max;
}
int main(void)
{
char *s1 = "(()";
char *s2 = ")()())";
char *s3 = "()(()";
printf("result of s1 : %d\n", longestValidParentheses(s1));
printf("result of s2 : %d\n", longestValidParentheses(s2));
printf("result of s3 : %d\n", longestValidParentheses(s3));
return 0;
}