|
1 | 1 | package com.thealgorithms.stacks;
|
2 | 2 |
|
3 |
| -// 1. You are given a string exp representing an expression. |
4 |
| -// 2. Assume that the expression is balanced i.e. the opening and closing brackets match with each |
5 |
| -// other. |
6 |
| -// 3. But, some of the pair of brackets maybe extra/needless. |
7 |
| -// 4. You are required to print true if you detect extra brackets and false otherwise. |
8 |
| -// e.g.' |
9 |
| -// ((a + b) + (c + d)) -> false |
10 |
| -// (a + b) + ((c + d)) -> true |
11 | 3 | import java.util.Stack;
|
12 | 4 |
|
| 5 | +/** |
| 6 | + * Class for detecting unnecessary or redundant brackets in a mathematical expression. |
| 7 | + * Assumes the expression is balanced (i.e., all opening brackets have matching closing brackets). |
| 8 | + */ |
13 | 9 | public final class DuplicateBrackets {
|
14 | 10 | private DuplicateBrackets() {
|
15 | 11 | }
|
16 | 12 |
|
17 |
| - public static boolean check(String str) { |
18 |
| - Stack<Character> st = new Stack<>(); |
| 13 | + /** |
| 14 | + * Checks for extra or redundant brackets in a given expression. |
| 15 | + * |
| 16 | + * @param expression the string representing the expression to be checked |
| 17 | + * @return true if there are extra or redundant brackets, false otherwise |
| 18 | + * @throws IllegalArgumentException if the input string is null |
| 19 | + */ |
| 20 | + public static boolean check(String expression) { |
| 21 | + if (expression == null) { |
| 22 | + throw new IllegalArgumentException("Input expression cannot be null."); |
| 23 | + } |
19 | 24 |
|
20 |
| - for (int i = 0; i < str.length(); i++) { |
21 |
| - char ch = str.charAt(i); |
| 25 | + Stack<Character> stack = new Stack<>(); |
| 26 | + for (int i = 0; i < expression.length(); i++) { |
| 27 | + char ch = expression.charAt(i); |
22 | 28 | if (ch == ')') {
|
23 |
| - if (st.peek() == '(') { |
| 29 | + if (stack.isEmpty() || stack.peek() == '(') { |
24 | 30 | return true;
|
25 |
| - } else { |
26 |
| - while (st.size() > 0 && st.peek() != '(') { |
27 |
| - st.pop(); |
28 |
| - } |
29 |
| - st.pop(); |
| 31 | + } |
| 32 | + while (!stack.isEmpty() && stack.peek() != '(') { |
| 33 | + stack.pop(); |
| 34 | + } |
| 35 | + if (!stack.isEmpty()) { |
| 36 | + stack.pop(); |
30 | 37 | }
|
31 | 38 | } else {
|
32 |
| - st.push(ch); |
| 39 | + stack.push(ch); |
33 | 40 | }
|
34 |
| - // System.out.println(st); |
35 | 41 | }
|
36 | 42 | return false;
|
37 | 43 | }
|
|
0 commit comments