Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding anagram using array list

Tags:

java

arraylist

I'm trying to find if two string are anagrams of each other:

void anagram(String a, String b) {
    List<Character> bcopy = new ArrayList<Character>();

    for (int i = 0; i < b.length(); i++)
        bcopy.add(b.charAt(i));
    if (b.length() == 0 || a.length() == 0) {
        System.out.println("Exit");
    } else {
        for (int i = 0; i < a.length(); i++) {
            char temp = a.charAt(i);
            if (bcopy.contains(temp)) {
                System.out.println("match found" + temp);
                bcopy.remove(temp);
            }
            for (char j : bcopy) {
                System.out.println("Values" + j);
            }
        }
    }
}

I keep getting an out of bounds error at the remove() line. Can someone please tell me how I reach the array bounds when I'm searching by the object availability? What am I missing here?

like image 889
P R Avatar asked May 31 '26 13:05

P R


2 Answers

The problem is you're using the int-argument version of remove() since the char temp is being treated as an int. Here's a workaround:

bcopy.remove(Character.valueOf(temp));

By the way a better way to test for anagrams would be something like:

char[] c1 = a.toCharArray();
char[] c2 = b.toCharArray();

Arrays.sort(c1);
Arrays.sort(c2);

return Arrays.equals(c1, c2);  // true -> anagram, false -> not anagram
like image 195
arshajii Avatar answered Jun 02 '26 01:06

arshajii


there is another algorithm which might be more suitable to the task. it computes the letter frequencies for strings of equal lengths. for simplicity i assume that the set of all characters involved can be represented in one of the common 8 bit codepages.

void anagram(String a, String b) {
    int    freqa[256], freqb[256];

    if (b.length() == 0 || a.length() == 0) {
        System.out.println("Exit");
        return;
    }

    for (int i = 0; i < b.length(); i++) {
        freqa[(int) a.charAt(i)]++;
        freqb[(int) b.charAt(i)]++;
    }

    for (i = 0; i < 256; i++) {
        if (freqa[i] <> freqb[i]) {
            System.out.println("Exit");
            return;
        }
    }
    System.out.println("match found: '" + a + "', '" + b + "'");
}
like image 23
collapsar Avatar answered Jun 02 '26 02:06

collapsar