forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathValidParentheses.java
More file actions
74 lines (67 loc) · 1.89 KB
/
ValidParentheses.java
File metadata and controls
74 lines (67 loc) · 1.89 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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package com.thealgorithms.stacks;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
/**
* Valid Parentheses Problem
*
* Given a string containing just the characters '(', ')', '{', '}', '[' and ']',
* determine if the input string is valid.
*
* An input string is valid if:
* 1. Open brackets must be closed by the same type of brackets.
* 2. Open brackets must be closed in the correct order.
* 3. Every close bracket has a corresponding open bracket of the same type.
*
* Examples:
* Input: "()"
* Output: true
*
* Input: "()[]{}"
* Output: true
*
* Input: "(]"
* Output: false
*
* Input: "([)]"
* Output: false
*
* @author Gokul45-45
*/
public final class ValidParentheses {
private ValidParentheses() {
}
/**
* Checks if the given string has valid parentheses
*
* @param s the input string containing parentheses
* @return true if valid, false otherwise
*/
public static boolean isValid(String s) {
if (s == null || s.length() % 2 != 0) {
return false;
}
Map<Character, Character> parenthesesMap = new HashMap<>();
parenthesesMap.put('(', ')');
parenthesesMap.put('{', '}');
parenthesesMap.put('[', ']');
Stack<Character> stack = new Stack<>();
for (char c : s.toCharArray()) {
if (parenthesesMap.containsKey(c)) {
// Opening bracket - push to stack
stack.push(c);
} else {
// Closing bracket - check if it matches
if (stack.isEmpty()) {
return false;
}
char openBracket = stack.pop();
if (parenthesesMap.get(openBracket) != c) {
return false;
}
}
}
// Stack should be empty if all brackets are matched
return stack.isEmpty();
}
}