-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvalidpar.java
More file actions
35 lines (33 loc) · 1.1 KB
/
validpar.java
File metadata and controls
35 lines (33 loc) · 1.1 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
import java.util.*;
public class validpar {
public boolean isValid1(String s) {
String st = s.replaceAll("\\s", "");
if (st.length() % 2 != 0) {
return false;
}
Stack<Character> stack = new Stack<>();
for (int i = 0; i < st.length(); i++) {
char ch = st.charAt(i);
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
}
else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
if ((ch == ')' && top != '(') || (ch == '}' && top != '{') || (ch == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter a string of parentheses:");
String str = in.nextLine();
validpar tr1 = new validpar();
System.out.println(tr1.isValid1(str));
}
}