-
Notifications
You must be signed in to change notification settings - Fork 0
/
20.valid-parentheses.c
65 lines (61 loc) · 1.27 KB
/
20.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
59
60
61
62
63
64
65
/*
* @lc app=leetcode id=20 lang=c
*
* [20] Valid Parentheses
*/
// @lc code=start
#include <string.h>
#include <stdbool.h>
#include <stdlib.h>
bool isValid(char *s)
{
int len = strlen(s);
if (len % 2 == 1)
{
return false;
}
char *trace = (char *)malloc(sizeof(char) * len);
int trace_idx = 0;
for (int i = 0; i < len; i++)
{
switch (s[i])
{
case '(':
case '[':
case '{':
trace[trace_idx++] = s[i];
break;
case ')':
if (trace_idx < 1 || trace[trace_idx - 1] != '(')
{
return false;
}
trace_idx--;
break;
case ']':
if (trace_idx < 1 || trace[trace_idx - 1] != '[')
{
return false;
}
trace_idx--;
break;
case '}':
if (trace_idx < 1 || trace[trace_idx - 1] != '{')
{
return false;
}
trace_idx--;
break;
default:
break;
}
}
return trace_idx == 0 ? true : false;
}
// @lc code=end
#include <stdio.h>
int main(int argc, char const *argv[])
{
printf("parentheses is %d \n", isValid("(("));
return 0;
}