-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy path20-valid-parentheses.java
More file actions
44 lines (38 loc) · 1.77 KB
/
20-valid-parentheses.java
File metadata and controls
44 lines (38 loc) · 1.77 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
import java.util.Stack;
import java.util.HashMap;
import java.util.Map;
class Solution {
// Approach: Stack
public boolean isValid(String s) {
Stack<Character> st = new Stack<>();
Map<Character, Character> mappings = new HashMap<>();
mappings.put(')', '(');
mappings.put('}', '{');
mappings.put(']', '[');
for (char c : s.toCharArray()) {
if (mappings.containsKey(c)) { // If it's a closing bracket
// The stack must not be empty, and the top of the stack must be the corresponding opening bracket
char topElement = st.empty() ? '#' : st.pop();
if (topElement != mappings.get(c)) {
return false;
}
} else { // It's an opening bracket
st.push(c);
}
}
// If the stack is empty, all opening brackets have been matched
return st.empty();
}
public static void main(String[] args) {
Solution sol = new Solution();
System.out.println("Testing Valid Parentheses:");
System.out.println("\"()\" -> " + sol.isValid("()") + " (Expected: true)");
System.out.println("\"()[]{}\" -> " + sol.isValid("()[]{\}") + " (Expected: true)");
System.out.println("\"(]\" -> " + sol.isValid("(]") + " (Expected: false)");
System.out.println("\"{[()]}\" -> " + sol.isValid("{[()]}") + " (Expected: true)");
System.out.println("\"([]){}\" -> " + sol.isValid("([]){}") + " (Expected: true)");
System.out.println("\"(())\" -> " + sol.isValid("(())") + " (Expected: true)");
System.out.println("\"{\" -> " + sol.isValid("{") + " (Expected: false)");
System.out.println("\"]\" -> " + sol.isValid("]") + " (Expected: false)");
}
}