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


#define IsLeft(a) (a=='(' || a=='{' || a == '[')
#define IsMatch(a,b) (a=='('&& b==')' \
|| a == '{' && b =='}' \
|| a=='[' && b == ']') //const char* p: the string that contains Parentheses //l: the length of the string bool IsValidParentheses(const char* p, int l) { if (l %2 == 1 || !IsLeft(*p))return false; char stack[l]; int index = 0; char c; while(*p) { c = *p++; if(IsLeft(c)) stack[index++] = c; else { //if Parentheses is match, pop stack if (IsMatch(stack[index-1],c)) --index; else return false; } } //the parentheses is valid if and only if //the stack is tempty in finally return index <= 0; } #include <stdio.h> int main(int argc, char** argv) { char a[]="[]{}"; char b[]="{[]()}"; char c[]="{{{}[]})"; printf("%s is %s Parentheses\n", a, IsValidParentheses(a,4)?"valid":"invalid"); printf("%s is %s Parentheses\n", b, IsValidParentheses(b,6)?"valid":"invalid"); printf("%s is %s Parentheses\n", c, IsValidParentheses(c,8)?"valid":"invalid"); return 0; }
View Program Text


Test Status