Skip to content

Commit 1316268

Browse files
Refine
Signed-off-by: begeekmyfriend <begeekmyfriend@gmail.com>
1 parent 82870a0 commit 1316268

File tree

1 file changed

+16
-19
lines changed

1 file changed

+16
-19
lines changed

032_longest_valid_parentheses/valid_parentheses.c

Lines changed: 16 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,37 @@
11
#include <stdio.h>
22
#include <stdlib.h>
33

4+
45
static int longestValidParentheses(char* s)
56
{
6-
int cap = 8000, error = -1;
7-
int length = 0, max_length = 0;
8-
char *p = s;
7+
int i, cap = 18000, invalid = -1;
8+
int len = 0, max_len = 0;
99
int *stack = malloc(cap * sizeof(int));
1010
int *top = stack;
1111

12-
while (*p != '\0') {
13-
if (*p == '(') {
14-
if (top + 1 - stack >= cap) {
15-
cap *= 2;
16-
stack = realloc(stack, cap * sizeof(int));
17-
}
18-
*top++ = p - s;
12+
/* We only restore index of '(' since restrain of space */
13+
for (i = 0; s[i] != '\0'; i++) {
14+
if (s[i] == '(') {
15+
*top++ = i;
1916
} else {
2017
if (top > stack) {
2118
if (--top == stack) {
22-
/* The stack never keep ')' so we use 'error' to record index */
23-
length = p - (s + error);
19+
/* distancd of the latest ')' */
20+
len = i - invalid;
2421
} else {
25-
/* The *(top - 1) is the index of the last kept '(' */
26-
length = p - (s + *(top - 1));
22+
/* distance of the remote '(' */
23+
len = i - *(top - 1);
2724
}
28-
if (length > max_length) {
29-
max_length = length;
25+
if (len > max_len) {
26+
max_len = len;
3027
}
3128
} else {
32-
error = p - s;
29+
/* record the index of last ')' but no push */
30+
invalid = i;
3331
}
3432
}
35-
p++;
3633
}
37-
return max_length;
34+
return max_len;
3835
}
3936

4037
int main(int argc, char **argv)

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy