Skip to content

Commit d629701

Browse files
committed
Valid Parentheses code
1 parent c831b5e commit d629701

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

Java/validParentheses.java

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import java.util.Scanner;
2+
import java.util.Stack;
3+
4+
public class validParentheses {
5+
6+
public static void main(String[] args) {
7+
8+
Scanner sc = new Scanner(System.in);
9+
10+
// Get input
11+
System.out.println("Enter a string of brackets:");
12+
String str = sc.nextLine();
13+
14+
boolean isValid = checkValidParentheses(str);
15+
16+
if (isValid) {
17+
System.out.println("The parentheses are valid!");
18+
} else {
19+
System.out.println("The parentheses are NOT valid!");
20+
}
21+
}
22+
23+
24+
public static boolean checkValidParentheses(String s) {
25+
Stack<Character> stack = new Stack<>();
26+
27+
for (char ch : s.toCharArray()) {
28+
if (ch == '(' || ch == '{' || ch == '[') {
29+
stack.push(ch);
30+
} else if (ch == ')' || ch == '}' || ch == ']') {
31+
if (stack.isEmpty()) return false;
32+
33+
char top = stack.pop();
34+
35+
if ((ch == ')' && top != '(') ||
36+
(ch == '}' && top != '{') ||
37+
(ch == ']' && top != '[')) {
38+
return false;
39+
}
40+
}
41+
}
42+
43+
return stack.isEmpty();
44+
}
45+
}
46+

0 commit comments

Comments
 (0)