forked from vishal8113/Hacktoberfest-2024
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidParenthesis
30 lines (28 loc) · 1.08 KB
/
ValidParenthesis
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
import java.util.Stack;
public class ValidParentheses {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (c == '(' || c == '{' || c == '[') {
stack.push(c); // Push opening brackets onto the stack
} else {
if (stack.isEmpty()) {
return false; // No matching opening bracket
}
char top = stack.pop();
// Check if the closing bracket matches the last opened bracket
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) {
return false;
}
}
}
return stack.isEmpty(); // Check if all opening brackets are matched
}
public static void main(String[] args) {
ValidParentheses solution = new ValidParentheses();
String s = "([]{})";
System.out.println("Is valid: " + solution.isValid(s)); // Output: true
}
}