-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathString21.java
More file actions
47 lines (43 loc) · 1.44 KB
/
String21.java
File metadata and controls
47 lines (43 loc) · 1.44 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
import java.util.*;
public class String21 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
System.out.println("Syntax Check:");
for (int k = 1; k <= n; k++) {
String expr = sc.nextLine();
char[] stack = new char[expr.length()];
int top = -1;
boolean valid = true;
for (int i = 0; i < expr.length(); i++) {
char ch = expr.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
stack[++top] = ch;
}
else if (ch == ')' || ch == '}' || ch == ']') {
if (top == -1) {
valid = false;
break;
}
char open = stack[top--];
if ((ch == ')' && open != '(') ||
(ch == '}' && open != '{') ||
(ch == ']' && open != '[')) {
valid = false;
break;
}
}
}
if (top != -1) {
valid = false;
}
if (valid) {
System.out.println(k + ". " + expr + " -> Valid");
} else {
System.out.println(k + ". " + expr + " -> Invalid");
}
}
sc.close();
}
}