forked from TheAlgorithms/Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBalancedBrackets.java
More file actions
93 lines (81 loc) · 2.46 KB
/
BalancedBrackets.java
File metadata and controls
93 lines (81 loc) · 2.46 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package com.thealgorithms.stacks;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* BalancedBrackets.java
* Optimized valid parenthesis checker
*
* Supports: (), [], {}, <>
*
* Rules:
* - Returns true if brackets are properly nested and matched.
* - Returns false for any non-bracket character.
* - Empty string is balanced.
* - Null input throws IllegalArgumentException.
*
* Time complexity: O(n)
* Space complexity: O(n) in worst case (stack contains all opening brackets).
*
* @author Basundhara
* @author <a href="https://github.com/coder-Basundhara">GitHub</a>
*/
public final class BalancedBrackets {
private BalancedBrackets() {
// Utility class
}
/**
* Returns true if {@code opening} and {@code closing} are matching bracket pair.
*
* @param opening opening bracket
* @param closing closing bracket
* @return true if matched
*/
public static boolean isPaired(char opening, char closing) {
return (opening == '(' && closing == ')')
|| (opening == '[' && closing == ']')
|| (opening == '{' && closing == '}')
|| (opening == '<' && closing == '>');
}
/**
* Checks if the input string has balanced brackets.
*
* @param input input string
* @return true if balanced
* @throws IllegalArgumentException when input is null
*/
public static boolean isBalanced(String input) {
if (input == null) {
throw new IllegalArgumentException("Input cannot be null");
}
if (input.isEmpty()) {
return true;
}
// Odd-length strings cannot be balanced
if ((input.length() & 1) == 1) {
return false;
}
Deque<Character> stack = new ArrayDeque<>();
for (char c : input.toCharArray()) {
switch (c) {
case '(':
case '[':
case '{':
case '<':
stack.push(c);
break;
case ')':
case ']':
case '}':
case '>':
if (stack.isEmpty() || !isPaired(stack.pop(), c)) {
return false;
}
break;
default:
// Any non-bracket character makes string invalid
return false;
}
}
return stack.isEmpty();
}
}