-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution.java
More file actions
60 lines (55 loc) · 1.96 KB
/
Copy pathSolution.java
File metadata and controls
60 lines (55 loc) · 1.96 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
class Solution {
public boolean isValid(String s) {
// If the length of the string is odd, it can't be a valid sequence
if (s.length() % 2 != 0)
return false;
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
// Push opening brackets onto the stack
if (c == '(' || c == '{' || c == '[') {
stack.push(c);
}
// Check for matching closing brackets
else {
// If the stack is empty, it means there’s no matching opening bracket
if (stack.isEmpty())
return false;
char top = stack.pop(); // Pop the most recent opening bracket
// Check for the matching pair
if ((c == ')' && top != '(') ||
(c == '}' && top != '{') ||
(c == ']' && top != '[')) {
return false; // Return false if there’s a mismatch
}
}
}
// If the stack is empty, all brackets are properly closed
return stack.isEmpty();
}
}
// class Solution {
// public boolean isValid(String s) {
// // If the length of the string is odd, it can't be a valid sequence
// if (s.length() % 2 != 0) return false;
// Stack<Character> stack = new Stack<>();
// for (char c : s.toCharArray()) {
// // If it's an opening bracket, push it to the stack
// if (c == '(' || c == '{' || c == '[') {
// stack.push(c);
// }
// // Check for matching closing brackets
// else if (c == ')' && !stack.isEmpty() && stack.peek() == '(') {
// stack.pop();
// } else if (c == '}' && !stack.isEmpty() && stack.peek() == '{') {
// stack.pop();
// } else if (c == ']' && !stack.isEmpty() && stack.peek() == '[') {
// stack.pop();
// } else {
// // If there's no match, return false
// return false;
// }
// }
// // If the stack is empty, all brackets have been matched
// return stack.isEmpty();
// }
// }