Wednesday, July 26, 2023

Java Anagrams

 Two strings,  and , 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

Returns

  • boolean: If  and  are case-insensitive anagrams, return true. Otherwise, return false.

Input Format

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

Constraints

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

Sample Input 0

anagram
margana

Sample Output 0

Anagrams

Explanation 0

CharacterFrequency: anagramFrequency: margana
A or a33
G or g11
N or n11
M or m11
R or r11

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

Sample Input 1

anagramm
marganaa

Sample Output 1

Not Anagrams

Explanation 1

CharacterFrequency: anagrammFrequency: marganaa
A or a34
G or g11
N or n11
M or m21
R or r11

The two strings don't contain the same number of a's and m's, so we print "Not Anagrams".

Sample Input 2

Hello
hello

Sample Output 2

Anagrams

Explanation 2

CharacterFrequency: HelloFrequency: hello
E or e11
H or h11
L or l22
O or o11

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


SOLUTION:

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

public class Solution {

   static boolean isAnagram(String A, String B) {
       if(A == null || B == null) {
           if(A != null || B != null) {
               return false;
           }
           return true;
       }
       A = A.toLowerCase();
       B = B.toLowerCase();
       char[] aArr = A.toCharArray();
       char[] bArr = B.toCharArray();
       Arrays.sort(aArr);
       Arrays.sort(bArr);
       String aSorted = new String(aArr);
       String bSorted = new String(bArr);
       
       return aSorted.equals(bSorted); 
       
       
   
   }
    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");
        
    }
}

No comments:

Post a Comment

Featured Post

14. Longest Common Prefix

Popular Posts