Anagram of String

Anagram of String

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

Sample input

cat

act

Output

Anagram

Code:

public Class Anagram{
public static void main(String[] args) {
    String a = "cat";
    String b = "act";
     boolean isAnagram = true;

    int[] al = new int[256];
    int [] bl = new int[256];
    /* for each loop*/for (char c1: a.toCharArray() /* it will return array of char*/) {
        int index = (int) c1;
        al[index]++;

    }
    /* for each loop*/ for (char c2: b.toCharArray() /* it will return array of char*/) {
        int index = (int) c2;
        bl[index]++;




    }

    for(int i= 0 ; i<256; i++) {
        if(al[i]!=bl[i]) {
            isAnagram = false;
            break;

        }
    }
    if(isAnagram) {
         System.out.println("Is Anagram");
     }else
     {
         System.out.println("Not anagram");
     }
}
}

I Hope you guys find helpful this code, Happy Coding

Thank You



Categories: HackerRank Questions

Tags: , ,

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: