Input Format

The first line contains a string denoting .
The second line contains a string denoting .

Constraints

  • Strings  and  consist of English alphabetic characters.
  • The comparison should NOT be case sensitive.

Output Format

Print "Anagrams" if  and  are case-insensitive anagrams of each other; otherwise, print "Not Anagrams" instead.


hackerrank java anagrams solution


Java Anagrams problem solution | HackerRank

import java.io.*;
import java.util.*;

public class Solution {

    static boolean isAnagram(String firstWord, String secondWord) {
     char[] word1 = firstWord.toLowerCase().replaceAll("[\\s]", "").toCharArray();
     char[] word2 = secondWord.toLowerCase().replaceAll("[\\s]", "").toCharArray();
     Arrays.sort(word1);
     Arrays.sort(word2);
     return Arrays.equals(word1, word2);
    }
    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);
        String A=sc.next();
        String B=sc.next();
        boolean ret=isAnagram(A,B);
        if(ret)System.out.println("Anagrams");
        else System.out.println("Not Anagrams");

    }
}

Second solution

import java.util.*;

public class Solution {

    static boolean isAnagram(String s1, String s2) {
        if (s1.length() != s2.length()) {
            return false;
        }
        
        char[] a = s1.toLowerCase().toCharArray();
        char[] b = s2.toLowerCase().toCharArray();
        boolean anagram = true;
        Arrays.sort(a);
        Arrays.sort(b);
        
        for(int i = 0; i < a.length; i++) {
            if(a[i] != b[i]) {
                anagram = false;
            }
        }
        
        return anagram;
    }
  
    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" );
    }
}