Two Strings are said to be anagram if you can form one string by arranging the characters of another string . For example : Earth and Heart , Care and Race, Keep and Peek etc.
Approach :
In this approach , the idea is that if two strings are anagram, then their characters will be the same , you have to just rearrange the characters. So,if you sort the characters of both the strings , the sorted strings will be same if both the strings are anagram.
EXAMPLE :
public class AnagramString {
public static void main( String args[] ) {
String str1=“Eleven plus two”;
String str2=“Twelve plus one”;
//To remove the space between words of the string
str1=str1.replaceAll(“\\s ” , ” “);
str2=str2.replaceAll(“\\s” , ” ” );
boolean status=true;
if(str1.length()!=str2.length() ) {
status=false;
}
else{
char ArrayS1[] =str1.toLowerCase().toCharArray();
char ArrayS2[] = str2.toLowerCase().toCharArray();
Arrays.sort(ArrayS1);
Arrays.sort(ArrayS2);
status = Arrays.equals(ArrayS1, ArrayS2 ) ;
}
if(status==true ) {
System.out.println(“Two Strings are anagram “);
}
else{
System.out.println(“Two Strings are not anagram”);
}
}
}
OUTPUT:
Two Strings are anagram.
