-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbalanced parenthesis hackerrank
More file actions
69 lines (62 loc) · 1.34 KB
/
balanced parenthesis hackerrank
File metadata and controls
69 lines (62 loc) · 1.34 KB
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
66
67
68
69
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#define MAX_SIZE 1000
struct stack {
char stk[MAX_SIZE];
int top;
} s;
void push(char c) {
if (s.top < MAX_SIZE) {
s.stk[++s.top] = c;
}
}
char pop() {
if (s.top > -1) {
return s.stk[s.top--];
} else {
return -1;
}
}
int balancedParentheses(char *s, int length) {
char target, c;
if (length % 2 != 0) {
return 0;
}
for(int i = 0; i < length; i++) {
if ((s[i]=='(') || (s[i]=='{') || (s[i]=='[')) {
push(s[i]);
} else {
switch(s[i]) {
case ')': target = '('; break;
case '}': target = '{'; break;
case ']': target = '['; break;
}
c = pop();
if (c == -1 || c != target) {
return 0;
}
}
}
return pop() == -1;
}
int main() {
int t, length;
char str[1000], c;
scanf("%d\n", &t);
for (int i = 0; i < t; i++) {
s.top = -1;
length = 0;
for (;;) {
c = getchar();
if (c == EOF || c == '\n') {
break;
}
str[length] = c;
length++;
}
printf("%s\n", balancedParentheses(str, length) == 0 ? "NO" : "YES");
}
return 0;
}