0

I am looking at the question "Write code to remove the duplicate characters in a string without using any additional buffer" in the cracking coding book.

I have written a program with the solution in the book:

public class test {
    public static void main(String[] args) {
        String str = "aaabbb";
        char[] charArray = str.toCharArray();
        System.out.println(charArray);
        remove_V(charArray);
        System.out.println(charArray);
    }

    public static void remove_V(char[] str) {
        if (str == null) return;
        int len = str.length;
        if (len < 2) return;
        int tail = 1;
        for (int i = 1; i < len; ++i) {
            int j;
            for (j = 0; j < tail; ++j) {
                if (str[i] == str[j]) break;
            }
            if (j == tail) {
                str[tail] = str[i];
                ++tail;
            }
        }
        str[tail] = 0;
    }

}

I tested the program with "aaabbb", but the output I got was "abbb". Does this mean the program is wrong?

Zack
  • 1,205
  • 2
  • 14
  • 38

2 Answers2

0

The problem is the last command of remove_V method. You are setting with '0' just the last position of str array determined by the last value of tail. Actually, it is necessary to clean all tail positions, i. e., from the position corresponding to the last value of tail through the last position of str array (len-1). So, change

str[tail] = 0;

to something like this

for (int i = tail; i < len; ++i)
    str[i] = 0;
tnas
  • 510
  • 5
  • 16
0

In this case you can use the java charAt() with one for loop, you don't need two just for loop and if block.

You need to make the logic simple with two things. one a previous value-- to store the previous char in it and if block to store char values that are not equal to the previous char.

public static void main(String[] args) {
    String str = "aaabbb";
    String str2 = "aaabbkkbmoouse";
    System.out.println(remDup(str));
    System.out.println(remDup(str2));
}

public static String remDup(String str){
    String res = "";  // final resulting groups of chars
    char prev = '-';
    for(int i = 0; i < str.length(); i++){
        if (str.charAt(i) != prev) {  // not equal to previous to store to previous and add to results.
            prev = str.charAt(i);
            res += prev;
        }

    }
    return res;
}

OUTPUT

str: ab

str2: abkbmouse

Seek Addo
  • 1,871
  • 2
  • 18
  • 30