Anagram Checking Logical Error - Cant seem to find the error

Viewed 59
public class AnagramUnoptimized {
  public static void main(String[] args) {

    String a  = "good";
    String b  = "ogod";
    boolean isAnagram = false;

    String c = a.toLowerCase();
    String d = b.toLowerCase();

    if(c.length()==d.length()) {
        boolean [] Visited = new boolean[a.length()];
        for (int i = 0; i < c.length(); i++) {
            isAnagram = false;
            for (int j = 0; j < d.length(); j++) {
                if (c.charAt(i) == d.charAt(j) && Visited[j]==false) {
                    isAnagram = true;
                    Visited[j] = true;
                }
            }
            if (isAnagram == false) {
                break;
            }
        }
    }
    if(isAnagram==true){
        System.out.println("The given Strings are Anagrams");
    }
    else{
        System.out.println("The given Strings are not Anagrams");
    }

  }
}

I used a Visited boolean array to check for repeated items but its now showing "Not anagram" for all inputs....

Can you tell me why its showing "Not anagram" if the strings have repeating elements??

2 Answers

The problem with your code is you are continuing with the loop even when visited[j] is changed to true whereas you need to break the inner loop at this point. Do it as follows:

for (int j = 0; j < d.length(); j++) {
    if (c.charAt(i) == d.charAt(j) && visited[j] == false) {
        isAnagram = true;
        visited[j] = true;
        break;
    }
}

The output after this change:

The given Strings are Anagrams

A better way to do it would be as follows:

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String a = "good";
        String b = "ogod";

        char[] first = a.toLowerCase().toCharArray();
        char[] second = b.toLowerCase().toCharArray();
        Arrays.sort(first);
        Arrays.sort(second);

        boolean isAnagram = Arrays.equals(first, second);

        if (isAnagram == true) {
            System.out.println("The given Strings are Anagrams");
        } else {
            System.out.println("The given Strings are not Anagrams");
        }
    }
}

Output:

The given Strings are Anagrams

In your code you should break the inner for loop when the condition "if (c.charAt(i) == d.charAt(j) && Visited[j]==false)" has been meet. Because it is still looping through the second stiring and if it will meet the same char one angain it will change the value of Visited[] to true two times, leading to an error. It this example this is the case witch char 'o'. Adding " break; " at the end of the if statement should fix the problem.

Related