This approach uses a stack to efficiently match opening and closing brackets. The stack stores opening brackets, and for each closing bracket encountered, it checks if it closes the last opened bracket (top of the stack).
Time Complexity: O(n), where n is the length of the string, since we process each character once.
Space Complexity: O(n) in the worst case if the string consists only of opening brackets.
1import java.util.Stack;
2
3public class Solution {
4 public boolean isValid(String s) {
5 Stack<Character> stack = new Stack<>();
6 for (char c : s.toCharArray()) {
7 if (c == '(' || c == '{' || c == '[') {
8 stack.push(c);
9 } else {
10 if (stack.isEmpty()) return false;
11 char top = stack.pop();
12 if ((c == ')' && top != '(') ||
13 (c == '}' && top != '{') ||
14 (c == ']' && top != '['))
15 return false;
16 }
17 }
18 return stack.isEmpty();
19 }
20}
The Java solution employs a stack to process and match each bracket in the string. If there's any imbalance or mismatched pair, it returns false.
This approach uses two pointers with stack-like behavior internally, taking advantage of simple list operations for push and pop.
Time Complexity: O(n)
Space Complexity: O(n/2) = O(n)
1public class Solution {
2 public boolean isValid(String s) {
3 if (s.length() % 2 != 0) return false;
4
5 StringBuilder stack = new StringBuilder();
6 for (char c : s.toCharArray()) {
7 if (c == '(' || c == '{' || c == '[') {
8 stack.append(c);
9 } else {
10 int length = stack.length();
11 if (length == 0) return false;
12 char top = stack.charAt(length - 1);
13 stack.deleteCharAt(length - 1);
14 if ((c == ')' && top != '(') ||
15 (c == '}' && top != '{') ||
16 (c == ']' && top != '['))
17 return false;
18 }
19 }
20 return stack.length() == 0;
21 }
22}
In Java, using StringBuilder along with character matching achieves similar stack manipulation while maintaining easy removability and appendability onto the existing stack representation.