-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy path01ValidParetheses.java
More file actions
31 lines (26 loc) · 967 Bytes
/
01ValidParetheses.java
File metadata and controls
31 lines (26 loc) · 967 Bytes
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
// Time complexity: O(n)
// Space complexity: O(n)
import java.util.Stack;
class Solution {
public boolean isValid(String s) {
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
// If c is an opening bracket, push it to the stack
if (c == '(' || c == '[' || c == '{') {
stack.push(c);
} else {
if (stack.isEmpty()) {
return false;
}
char top = stack.pop();
// If c is a closing bracket, check if it matches the top of the stack
// If not, return false (invalid)
if ((c == ')' && top != '(') || (c == ']' && top != '[') || (c == '}' && top != '{')) {
return false;
}
}
}
// If the stack is empty, the string is valid because all brackets are matched
return stack.isEmpty();
}
}