-4

it is a program for removing duplicate characters from a string ... i just don't understand what flag[str[cur]] it refers to...

class Cc1_3 {
    static String removeDup(String target) {    
        if (target == null) return null;    
        if (target.length() <= 1) return target;    
        char[] str = target.toCharArray();    
        boolean[] flag = new boolean[256];    
        int tail = 0;    
        int cur = 0;    
        while (cur < str.length) {    
            if (flag[str[cur]] == false) {    
                flag[str[cur]] = true;    
                str[tail] = str[cur];    
                tail++;    
                cur++;    
            } else cur++;    
        }    
        return new String(str, 0, tail);    
    }

    public static void main(String[] args) {    
        String test = "aabcdeaefgf";    
        System.out.println(removeDup(test));    
    }
}
Bhesh Gurung
  • 50,430
  • 22
  • 93
  • 142
xpedia
  • 1

3 Answers3

0

So you have 2 arrays. One array contains all the characters and one array containing booleans.

In java chars are 16 bit. Integers are 32 bit. So you can assign a char to an int in Java without any problems. You ca find more information about this here.

So what happens is:

1) First he loops over all the characters in the input String. 2) Next he checks in the boolean array if the char number (which will always be the same for the same characters) is false. Meaning it hasn't passed by yet.

So if the char was found the specific index of boolean array will be set to true and the if will fail the next time the char passed by again.

Community
  • 1
  • 1
Joel Witteveen
  • 387
  • 1
  • 9
0

Target string to char array str[],so (str[cur] )could be as integer index in the boolean array which are initial to false. So when the index in boolean array "value ==false" are not duplicate characters.

leometal
  • 29
  • 5
0

I believe all indexes in the flag array of booleans are initially set to false. When the program encounters flag[str[cur]] it will get the character in the str array and if the character has been found previously flag[str[cur]] will evaluate to true and will be skipped ie str = ['a','b','a','d'] and flag = [false,false,false,false]. When flag[str[cur]] is run, at index 0 it is false since 'a'(equivalent to flag['a'])has not been encountered before. After this index 0 or flag['a'] becomes true. For 'b' the same thing happens. When 'a' is reached again it checks flag['a'] again. Since this is already true it is skipped and cur is incremented. Hope this helped.

wahiddudin
  • 103
  • 6