HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaModerate

Eliminate duplicates from strings

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
fromeliminateduplicatesstrings

Problem

I have written a piece of code for removing duplicated values from a string. Any suggestions on improvements?

public static String removeDuplicate(String s)
{
    char [] temp = s.toCharArray();
    int length =temp.length; 
    for (int i=0;i<length;i++)
    {
        for (int j = i+1; j<length;j++)
        {
            if(temp[i]==temp[j])
            {
                int test =j;
                for(int k=j+1; k<length ; k++)
                {
                    temp[test] = temp[k];
                    test++;
                }
                length--;
                j--;
            }
        }
    }
    return String.copyValueOf(temp).substring(0,length);
}

Solution

Yusshi's code is perfectly fine. If you know that all the characters are in a specific range (e.g., ASCII code 0 to 255), you could also use either of the following codes which is faster. They uses an array rather than a hash set. The time complexity is O(n) and the space complexity is O(1). You cannot go lower in either case.

This one sorts the characters in the output string:

public static String removeDuplicates(String str) {
    int charsCount[] = new int[256];

    for (int i = 0; i  0) {
            sb.append((char)i);
        }
    }

    return sb.toString();
}


This one preserves the order of the characters:

public static String removeDuplicates(String str) {
    boolean seen[] = new boolean[256];
    StringBuilder sb = new StringBuilder(seen.length);

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if (!seen[ch]) {
            seen[ch] = true;
            sb.append(ch);
        }
    }

    return sb.toString();
}

Code Snippets

public static String removeDuplicates(String str) {
    int charsCount[] = new int[256];

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        charsCount[ch]++;
    }

    StringBuilder sb = new StringBuilder(charsCount.length);
    for (int i = 0; i < charsCount.length; i++) {
        if (charsCount[i] > 0) {
            sb.append((char)i);
        }
    }

    return sb.toString();
}
public static String removeDuplicates(String str) {
    boolean seen[] = new boolean[256];
    StringBuilder sb = new StringBuilder(seen.length);

    for (int i = 0; i < str.length(); i++) {
        char ch = str.charAt(i);
        if (!seen[ch]) {
            seen[ch] = true;
            sb.append(ch);
        }
    }

    return sb.toString();
}

Context

StackExchange Code Review Q#46777, answer score: 17

Revisions (0)

No revisions yet.