HackerRank: Java Anagrams

 Two strings, a and b, are called anagrams if they contain all the same characters in the same frequencies. For this challenge, the test is not case-sensitive. For example, the anagrams of CAT are CAT, ACT, tac, TCA, aTC, and CtA.

Function Description:

Complete the isAnagram function in the editor.

isAnagram has the following parameters:

  • string a: the first string
  • string b: the second string


Sample Input 0

anagram

margana

Sample Output 0

Anagrams


Character Frequency: anagram Frequency: margana

A or a 3 3

G or g 1 1

N or n 1 1

M or m 1 1

R or r 1 1

The two strings contain all the same letters in the same frequencies, so we print "Anagrams".


Java Code:

import java.util.Scanner;

public class javaAnagrams {
    static boolean isAnagram(String a, String b) {
       
        a=a.toUpperCase();
        b=b.toUpperCase();

        int aCount[] = new int[128];
        for(int i=0;i<a.length();i++)
        {
            aCount[a.charAt(i)]++;
        }
        int bCount[] = new int[128];
        for(int i=0;i<b.length();i++)
        {
            bCount[b.charAt(i)]++;
        }

        for(int i=0;i<bCount.length;i++)
        {
            if(aCount[i] != bCount[i])
            {
                return false;
            }
        }

        return true;
    }

    public static void main(String[] args) {
   
        Scanner scan = new Scanner(System.in);
        String a = scan.next();
        String b = scan.next();
        scan.close();
        boolean ret = isAnagram(a, b);
        System.out.println( (ret) ? "Anagrams" : "Not Anagrams" );
    }
}

No comments:

Post a Comment

HTML Forms - Input Types - Cheat Sheet

Popular Posts