An Anagram is a word formed by reshuffling or rearranging the letters of a different word; the vital point in an anagram is that the letters can be used only once and should not be repeated in the new word. An Anagram is a word having the same number of letters. The count here matters a lot. Anagram program in Java can be used in the above ways by sorting and comparing the two strings. If these succeed, then it means that the string is an anagram.
Start Your Free Software Development Course
Web development, programming languages, Software testing & others
Algorithm:
Let us have a look at the algorithm of getting an anagram from a specific word. There are three ways in which an anagram can be found out. We will explain all three ways, one by one. The basic algorithm consists of checking the lengths of the strings. Once the length is the same, it can be sorted or counted and checked for an anagram.
The first thing that we can do for the given strings is to sort both given strings that are to be verified if they are anagrams. Once the sorting is done, then it can be compared in the sorted orders. The time complexity for this method is O (n Logn). The Java code for this can be written as below:
Code:
// JAVA program to validate if two strings are anagrams import java.io.*; import java.util.Arrays; import java.util.Collections; class Main { /* Below is a function which checks if the strings are anagram */ static boolean checkAnagram(char[] strana1, char[] strana2) { // Finding lengths of strings int len1 = strana1.length; int len2 = strana2.length; // If lengths do not match then they cannot be anagrams if (len1 != len2) return false; // Sort both strings Arrays.sort(strana1); Arrays.sort(strana2); // Comparing the strings which are sorted earlier for (int i = 0; i < len1; i++) if (strana1[i] != strana2[i]) return false; return true; } /* Main program to test Anagram*/ public static void main (String args[]) { char strana1[] = { 't', 'e', 's', 't' }; char strana2[] = { 't', 't', 'e', 'w' }; if (checkAnagram(strana1, strana2)) System.out.println("The strings to be checked are" + " anagram of each other"); else System.out.println("The strings to be checked are not" + " anagram of each other"); } }
The above program first checks for the lengths of both given strings. If the strings are not having the same length, then it will return false. Only if the length’s of both strings are the same, then the program will progress further. By using the array sort function, it will sort the strings in two arrays. Once the array sort function is used on both strings, then the strings are compared, and each letter is compared in for a loop. If the for loop is successful and all letters in both strings are the same, then the output will be an anagram. Even if one letter does not match, then it will return false. The main program here checks for the strings and displays if the string is an anagram or not depending on the result returned by the checkAnagram function.
Output:
If we change the input to ‘t’, ‘t’, ‘e’, ‘s’ instead of w the output will be as below.
Output:
This method can be used when the strings under validation are small. This method considers that the characters stored are 8 bit and can store possibly 256 characters. In this method, you can first count the strings using the count arrays having size 256 and initialize all the necessary values in the count array as 0. Traverse through this array and increment the count while traversing. Once this is done, you can compare the count arrays. If the count is the same, then the result returned will be true.
Code:
import java.io.*; import java.util.*; class ANA { static int NO_CHARS = 256; /* Below is a function which checks if the strings are anagram */ static boolean isAnagram(char strana1[], char strana2[]) { // Here we create two arrays and initialize it to 0 int cnt1[] = new int[NO_CHARS]; Arrays.fill(cnt1, 0); int cnt2[] = new int[NO_CHARS]; Arrays.fill(cnt2, 0); int i; // For every character in input strings, increment the count for (i = 0; i < strana1.length && i < strana2.length; i++) { cnt1[strana1[i]]++; cnt2[strana2[i]]++; } // Checking If both strings are of different length if (strana1.length != strana2.length) return false; // Compare count arrays for (i = 0; i < NO_CHARS; i++) if (cnt1[i] != cnt2[i]) return false; return true; } /* Main program to test to check if string is Anagram or not*/ public static void main(String args[]) { char strana1[] = ("silent").toCharArray(); char strana2[] = ("lisent").toCharArray(); if (isAnagram(strana1, strana2)) System.out.println("The strings to be checked are" + " anagram of each other"); else System.out.println("The strings to be checked are not" + " anagram of each other"); } }
Output:
Anagram can be checked by using the StringBuilder function in Java. We can make use of the deletechartAt() method in order to delete any characters which are present in the second string.
Code:
public class Main { static void findAnagram(String str1, String str2) { String copystr1 = str1.replaceAll( " ", "").toLowerCase(); String copystr2 = str2.replaceAll(" ", "").toLowerCase(); //Setting the initial status to true boolean flag = true; if(copystr1.length() != copystr2.length()) { //If copystr1 and copystr2 do not have same length then set the flag to false flag = false; } else { //changing copystr1 to char array char[] str1Array = copystr1.toCharArray(); //Creating StringBuilder from copystr2 StringBuilder sb = new StringBuilder(copystr2); //Validating if each character of str1Array is present in string builder for (char c : str1Array) { int index = sb.indexOf(""+c); if (index != -1) { sb = sb.deleteCharAt(index); } else { //If each character is not present, setting flag to false and breaking the loop flag = false; break; } } } if(flag) { System.out.println(str1+" and "+str2+" are anagrams"); } else { System.out.println(str1+" and "+str2+" are not anagrams"); } } public static void main(String[] args) { findAnagram("Silent", "Listen"); } }
The program here uses the flag and uses a string builder module that helps delete extra characters.
Output:
The above is the detailed content of Anagram Program in Java. For more information, please follow other related articles on the PHP Chinese website!