In this HackerRank Java Anagrams problem in the java programming language, 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.
HackerRank Java Anagrams problem solution.
import java.util.Scanner; public class Solution { static boolean isAnagram(String s1, String s2) { // Complete the function s1=s1.toLowerCase(); s2=s2.toLowerCase(); if(s1.length()==s2.length()) { int[] a = new int[256]; int[] b = new int[256]; for (int i = 0; i < s1.length(); i++) { a[(int) s1.charAt(i)] += 1; b[(int) s2.charAt(i)] += 1; } for (int i = 0; i < 256; i++) { if (a[i] != b[i]) return false; } 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" ); } }
Second solution
import java.io.*; import java.util.*; public class Solution { static boolean isAnagram(String A, String B) { char[] arrA = A.toUpperCase().toCharArray(); char[] arrB = B.toUpperCase().toCharArray(); Arrays.sort(arrA); Arrays.sort(arrB); for(int i = 0; i < A.length(); i++) try { if(Character.toUpperCase(arrA[i]) != Character.toUpperCase(arrB[i])) return false; } // end try catch(Exception e) { return false; } // end catch return true; } // end isAnagram 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"); } // end main } // end class
A solution in java8 programming.
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"); } }
The first one is the most optimal solution.
The approach one can be optimized by using just one array only for the first string you increment the count at appropriate positions and then for the second string decrement the count. Finally check if all the elements are empty.
why is 256 written in
int[] a = new int[256];
I like the last one most. It's crisp.
In the 1st solution , why you initiallize the two int arrays as value 256