-
Notifications
You must be signed in to change notification settings - Fork 4k
Expand file tree
/
Copy pathvalidParentheses.java
More file actions
46 lines (33 loc) · 1.25 KB
/
validParentheses.java
File metadata and controls
46 lines (33 loc) · 1.25 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
import java.util.Scanner;
import java.util.Stack;
public class validParentheses {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Get input
System.out.println("Enter a string of brackets:");
String str = sc.nextLine();
boolean isValid = checkValidParentheses(str);
if (isValid) {
System.out.println("The parentheses are valid!");
} else {
System.out.println("The parentheses are NOT valid!");
}
}
public static boolean checkValidParentheses(String s) {
Stack<Character> stack = new Stack<>();
for (char ch : s.toCharArray()) {
if (ch == '(' || ch == '{' || ch == '[') {
stack.push(ch);
} else if (ch == ')' || ch == '}' || ch == ']') {
if (stack.isEmpty()) return false;
char top = stack.pop();
if ((ch == ')' && top != '(') ||
(ch == '}' && top != '{') ||
(ch == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty();
}
}