Remove the parentheses in Java

The challenge

In this challenge you are given a string for example:

"example(unwanted thing)example"

Your task is to remove everything inside the parentheses as well as the parentheses themselves.

The example above would return:

"exampleexample"

Notes

  • Other than parentheses only letters and spaces can occur in the string. Don’t worry about other brackets like "[]" and "{}" as these will never appear.
  • There can be multiple parentheses.
  • The parentheses can be nested.

The solution in Java code

Option 1:

public class Solution {
    public static String removeParentheses(final String str) {
        String updated = str.replaceAll("\\([^()]*\\)", "");
        if (updated.contains("(")) updated = removeParentheses(updated);     
        return updated;
    }
}

Option 2:

public class Solution {
    public static String removeParentheses(final String str) {
        
    String res = "";
    int count = 0;
    for (int l = 0; l < str.length(); l++) {
        char c = str.charAt(l);
        if (c == '(') count += 1;
        if (count == 0) res += str.charAt(l);
        if (c == ')') count -= 1;
    }
    return res;
    }
}

Option 3:

public class Solution {
    public static String removeParentheses(final String str) {
        String result = str;

        while (result.contains("(")) {
            result = result.replaceAll("\\([^()]*\\)", "");
        }
        return result;
    }
}

Test cases to validate our solution

import org.junit.Test;
import java.util.*;
import java.util.stream.*;

public class SolutionTest {
    @Test
    public void fixedTests() {
        for (String[] trial : new String[][]{
                {"example(unwanted thing)example", "exampleexample"},
                {"example(unwanted thing)example", "exampleexample"},
                {"example (unwanted thing) example", "example  example"},
                {"a (bc d)e", "a e"},
                {"a(b(c))", "a"},
                {"hello example (words(more words) here) something", "hello example  something"},
                {"(first group) (second group) (third group)", "  "}})
            Tester.doTest(trial[0], trial[1]);
    }
    private static final String letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ   ";
    private static final Random rand = new Random();
    private static String randomLetter() {
        int i = rand.nextInt(letters.length());
        return letters.substring(i, i+1);
    }
    @Test
    public void randomTests() {
        for (int trial = 1; trial <= 100; trial++) {
            String str = IntStream.range(0, rand.nextInt(200)+2)
                                  .mapToObj(i -> randomLetter())
                                  .collect(Collectors.joining(""));
            for (int parens = rand.nextInt(str.length()/2); 0 < parens--;) {
                int open = rand.nextInt(str.length()-1), close = rand.nextInt(str.length()-open) + open;
                str = str.substring(0, open) + "(" + str.substring(open, close) + ")" + str.substring(close);
            }
            Tester.doTest(str, solution(str));
        }
    }
    private String solution(final String str) {
        StringBuilder sb = new StringBuilder();
        int depth = 0;
        for (char c : str.toCharArray()) {
            depth += '(' == c ? 1 : 0;
            if ( 0 == depth ) sb.append(c);
            depth -= ')' == c ? 1 : 0;
        }
        return sb.toString();
    }
}
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments