Check if 2 strings are anagram

An anagram of a string is another string that contains the same characters, only the order of characters can be different. For example, “abcd” and “dabc” are an anagram of each other.

class isStringAnagram {

    // Asumption : All characters in strings are ASCII codes

    static void isAnagram(String str1, String str2) {

        if(str1.length() != str2.length()) {

            System.out.println(str2 + " is not anagram of " + str1);

            return; // early return

        }

        int[] frequency = new int[128];

        for(int i = 0; i < str1.length(); i++) {

            frequency[str1.charAt(i)]++;

        }

        for(int i = 0; i < str1.length(); i++) {

            if(frequency[i] == 0) {

                System.out.println(str2 + " is not anagram of " + str1);

                return; // early return

            }

            frequency[str2.charAt(i)]--;

        }

        for(int i = 0; i < 128; i++) {

            if(frequency[i] != 0) {

                System.out.println(str2 + " is not anagram of " + str1);

                return;

            }

        }

        System.out.println(str2 + " is anagram of " + str1);

    }

public static void main (String[] args) {

String str1 = "Raghav Mishra";

String str2 = "Mishra Raghav";

        isAnagram("Raghav Mishra", "Mishra Raghav");

        isAnagram("Raghav", "Mishra");

}

}

Comments

Popular posts from this blog

SQL basic interview question

gsutil Vs Storage Transfer Service Vs Transfer Appliance