Java Anagrams

Two strings  and  are called anagrams if they consist same characters, but may be in different orders. So the list of anagrams of  is .
Given two strings, print Anagrams if they are anagrams, print Not Anagrams if they are not. The strings may consist at most  English characters; the comparison should NOT be case sensitive.
This exercise will verify that you can sort the characters of a string, or compare frequencies of characters.
Sample Input 0
anagram
margana
Sample Output 0
Anagrams
Sample Input 1
anagramm
marganaa
Sample Output 1:
Not Anagrams..

Program:

import java.io.*;import java.util.*;
public class Solution {
public class Solution {
    public static boolean isAnagram(String s, String s1) {
        
        
        char[] ax = s.toLowerCase().toCharArray();
        char[] a1 = s1.toLowerCase().toCharArray();
        Arrays.sort(ax);Arrays.sort(a1);int c = 0;
        String r = new String(ax);
        String r1 = new String(a1);
        //System.out.println(r+" "+r1);
        
        if(r.equals(r1))
        {
            return true;
        }
        else
            return false;
    }
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" );
    }
}

Comments

Popular Posts