0

I am an Intermediate in programming. I'm a few weeks into my first programming class, so please bear with me. I am not a person to ask for help, so I have searched for an answer extensively with no luck. This is also my first time posting anything in any type of forum, so if my question structure is off I'm sorry and I will correct for future posts.

public class removeDuplicate5 {
    public static boolean[] map = new boolean[26];

    public static void removeDuplicates(String str, int idx, String newString) {
        if (idx == str.length()) {
            System.out.println(newString);
            return;
        }
        char currChar = str.charAt(idx);
        if (map[currChar - 'a']) {
            removeDuplicates(str, idx + 1, newString);
        } else {
            newString += currChar;
            map[currChar - 'a'] = true;
            removeDuplicates(str, idx + 1, newString);
        }
    }

    public static void main(String[] args) {
        String company = "Inxee";
        removeDuplicates(company, 0, "");
    }
}
ODDminus1
  • 544
  • 1
  • 3
  • 11
Parvez
  • 1
  • 2

3 Answers3

0

Your implementation only works for small case letters since you have used the condition:

if (map[currChar - 'a'])

If you use upper case letters, the ascii values for those will be greater than that of a. So, currChar - a will result in a negative number resulting in array index out of bound exception.

hermit
  • 1,048
  • 1
  • 6
  • 16
0

public class RemoveDuplicatesExample {

// I have assumed that the character range is lowercase English letters

static boolean[] map = new boolean[26];

/*Here I have initialized the array map where it's size needs to be determined here, I'm accessing 26 lowercase english alphabet letters */

public static void removeDuplicates(String str, int idx, String newString) {
    if (idx == str.length()) {
        System.out.println(newString);
        return;
    }
    char currChar = str.charAt(idx);
    if (map[currChar - 'a']) {
        removeDuplicates(str, idx + 1, newString);
    } else {
        newString += currChar;
        map[currChar - 'a'] = true;
        removeDuplicates(str, idx + 1, newString);
    }
}

public static void main(String[] args) {
    String company = "Inxee";
    removeDuplicates(company, 0, "");
}

}

0

This will work for you. Only 2 lines need to be changed.

public static void removeDuplicates(String str, int idx, String newString) {
    if (idx == str.length()) {
        System.out.println(newString);
        return;
    }
    char currChar = str.charAt(idx);
    if (newString.indexOf(currChar) >= 0) {
        removeDuplicates(str, idx + 1, newString);
    } else {
        newString += currChar;
        removeDuplicates(str, idx + 1, newString);
    }
}

public static void main(String[] args) {
    String company = "Inxee";
    String newString = "";
    removeDuplicates(company, 0, newString);
    System.out.println(newString);
}