Check whether two strings are anagram of each other or not

package chalanges.compitative;import java.util.Arrays;/**
*
* @author SivaReddy Uppathi
*/
public class Anagram {
public static void main(String[] args) {
char str1[] = {'s', 'i', 'v', 'a'};
char str2[] = {'s', 'v', 'a', 'i'};
boolean isAnagram = checkAnagramUsingSorting(str1, str2);
System.out.println(isAnagram);
}private static boolean checkAnagramUsingSorting(char[] str1, char[] str2) {
if (str1.length != str2.length) {
return false;
}
Arrays.sort(str1);
Arrays.sort(str2);
for (int i = 0; i < str1.length; i++) {
if (str1[i] != str2[i]) {
return false;
}
}
return true;
}
}
private static boolean checkAnagramByCharCount2Arrays(char[] str1, char[] str2) {
if (str1.length != str2.length) {
return false;
}
int count1[] = new int[256];
Arrays.fill(count1, 0);
int count2[] = new int[256];
Arrays.fill(count2, 0);
for (int i = 0; i < str1.length; i++) {
count1[str1[i]]++;
count2[str2[i]]++;
}
for (int i = 0; i < NO_OF_CHARS; i++) {
if (count1[i] != count2[i]) {
return false;
}
}
return true;
}
private static boolean checkAnagramByCharCount1Array(char[] str1, char[] str2) {
if (str1.length != str2.length) {
return false;
}
int[] count = new int[256];
for (int i = 0; i < str1.length; i++) {
count[str1[i] - 'a']++;
count[str2[i] - 'a']--;
}
for (int i = 0; i < NO_OF_CHARS; i++) {
if (count[i] != 0) {
return false;
}
}
return true;
}
private static boolean checkAnagramBySum(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
int count = 0;
for (int i = 0; i < str1.length(); i++) {
count = count + str1.charAt(i);
}
for (int i = 0; i < str2.length(); i++) {
count = count - str2.charAt(i);
}
return (0 == count);
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store