Skip to content

Commit

Permalink
Longest valid parentheses
Browse files Browse the repository at this point in the history
Signed-off-by: begeekmyfriend <[email protected]>
  • Loading branch information
begeekmyfriend committed Jul 28, 2017
1 parent 03288e9 commit c595f87
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 0 deletions.
2 changes: 2 additions & 0 deletions 032_longest_valid_parentheses/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
all:
gcc -O2 -o test valid_parentheses.c
41 changes: 41 additions & 0 deletions 032_longest_valid_parentheses/valid_parentheses.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#include <stdio.h>
#include <stdlib.h>

static int longestValidParentheses(char* s) {
int cap = 1, error = -1;
int length = 0, max_length = 0;
char *p = s;
int *stack = malloc(cap * sizeof(int));
int *top = stack;

while (*s != '\0') {
if (*s == '(') {
if (top + 1 - stack >= cap) {
cap *= 2;
stack = realloc(stack, cap * sizeof(int));
}
*top++ = s - p;
} else {
if (top > stack) {
if (--top == stack) {
length = s - p - error;
} else {
length = s - p - *(top - 1);
}
if (length > max_length) {
max_length = length;
}
} else {
error = s - p;
}
}
s++;
}
return max_length;
}

int main(int argc, char **argv)
{
printf("%d\n", longestValidParentheses(argv[1]));
return 0;
}

0 comments on commit c595f87

Please sign in to comment.