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

Review on code for duplicate removal

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

Problem

I am trying to remove duplicates from a string without using additional buffers.

This seems to work correct, I think. Can this be improved? Should I be doing it differently?

private static String removeDuplicates(char[] chars) {  

        if(chars == null) 
            return null;

        int len = chars.length;         
        for(int i = 0; i < len; i++){
            for(int j = i + 1; j < len;){
                if(chars[i] == chars[j]){
                    int temp = j;
                    while(temp < len - 1){
                        chars[temp] = chars[temp + 1];
                        temp++;
                    }
                    len--;
                }
                else
                    j++;
            }
        }

        return new String(chars, 0, len);
    }

Solution

A few stylistic comments :

-
I'd change the while loop for a for loop. It doesn't matter at all but I feel it better that way.

-
You could perform len--; before the while (or for) loop so that you can go til len instead of len - 1.

Then, as duplicates don't need to be close to each other (from what I understand), wouldn't it be easier to do something like (NOT TESTED AT ALL) :

private static String removeDuplicates(char[] chars) {  
    if(chars == null) 
        return null;
    int len = chars.length;
    int idx = 0;         
    for (int i = 0; i < len; i++) {
        char c = chars[i];
        bool dup = false;
        for (int j = 0; j < idx; j++) {
            if (c == chars[j]) {
                dup = true;
                break;
            }
        }
        if (!dup) {
            chars[idx] = c;
            idx++;
        }
    }

    return new String(chars, 0, idx);
}


The point would be to go through the string and for each characters, try to see if we have seen it already. If we haven't we store it, otherwise, we don't.

Code Snippets

private static String removeDuplicates(char[] chars) {  
    if(chars == null) 
        return null;
    int len = chars.length;
    int idx = 0;         
    for (int i = 0; i < len; i++) {
        char c = chars[i];
        bool dup = false;
        for (int j = 0; j < idx; j++) {
            if (c == chars[j]) {
                dup = true;
                break;
            }
        }
        if (!dup) {
            chars[idx] = c;
            idx++;
        }
    }

    return new String(chars, 0, idx);
}

Context

StackExchange Code Review Q#7173, answer score: 4

Revisions (0)

No revisions yet.