0

I am new to Java and am trying to create a method that will allow me to remove duplicate characters in a string and create a new string with all the consecutive occurrences of the same character turned into a single character. For example, string fffggghhh would return as fgh. I have provided my code below but I am receiving an index out of range error with the length of the string that I input. For example when testing this method and entering AA as my string, I receive an index out of range 2 error.

public String DuplicatesTEST(String s) {
    StringBuilder result = new StringBuilder();
    for (int i = 1; i <= s.length(); i++) {
        char curr = s.charAt(i);
        char prev = s.charAt(0);
        if (curr != prev) {
            result.append(prev);
        } else if (curr == prev)
            prev = curr;
    }
    return result.toString();
}
0

3 Answers 3

2

Behavior of Data structure Set is not containing duplicates, so use Set to remove duplicates.
Try something like this:

public String DuplicatesTEST(String s) {
    Set<Character> set = new HashSet<>();
    StringBuilder result = new StringBuilder();
    for (int i = 0; i < s.length(); i++) {
        set.add(s.charAt(i));
    }
    set.forEach(result::append);
    return result.toString();
}

for fffggghhhff input this return fgh.

If you want to remove duplicates with a block above solution not help then I did small change to your implementation:

public String DuplicatesTEST(String s) {
    StringBuilder result = new StringBuilder();
    if (s != null && !s.isEmpty()) {
        char first = s.charAt(0);
        for (int i = 1; i < s.length(); i++) {
            if (first != s.charAt(i)) {
                result.append(first);
                first = s.charAt(i);
            }
        }
        result.append(first);
    }
    return result.toString();
}

for fffggghhhff input this return fghf.

Sign up to request clarification or add additional context in comments.

3 Comments

@ScaryWombat Thank your comment I updated the answer and add small note.
Although I think the OP only wants to remove duplicate consecutive chars with all the consecutive occurrences of the same character turned into a single character.
@ScaryWombat thanks I hope I understand what you mean.
1

You can transform your method to recursive and use regexp. This greatly simplifies your code.

Try it online!

public static String removeDuplicates(String str) {
    if (str.equals(str = str.replaceAll("(.)\\1", "$1")))
        return str;
    else
        return removeDuplicates(str);
}
public static void main(String[] args) {
    System.out.println(removeDuplicates("aaaaaaa"));     // a
    System.out.println(removeDuplicates("fffggghhh"));   // fgh
    System.out.println(removeDuplicates("fffggghhhff")); // fghf
}

Explanation:

  • regexp (.)\\1 - any character followed by the same character;
    • regexp $1 - replace with a character from the 1st group, i.e. the same character;
  • str = str.replaceAll(...) - removes all duplicates and replaces current string;
  • str.equals(...) - checks equality of the current string with itself, but without duplicates.

See also: Remove a pair of chars in a string next to each other

Comments

0

Strings are 0 based Index.

As per your input, If duplicate characters are consecutive orders then you can store first character from your input string into result StringBuilder.

Also, in your code, prev always stars at 0 which is wrong. You need to keep increment it too.

Here is is fixed version of your code:

public static String DuplicatesTEST(String s) {
    StringBuilder result = new StringBuilder();
    result.append(s.charAt(0));
    for (int i = 1; i < s.length(); i++) {
        char prev = s.charAt(i);
        char curr = s.charAt(i - 1);
        if (curr != prev || i == 0) {
            result.append(prev);
        }
        else if (curr == prev) {
            prev = curr;
        }
    }
    return result.toString();
}

1 Comment

FYI - you don't need else if condition here because if current and previous characters are different then you want to add in your result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.