Find two strings are anagram in Java ?
Source Code :
import java.util.Arrays;
/**
* Anagram.java
* @author Shashwat Anand
*/
public class Anagram {
public static void main(String[] args) {
System.out.println(testAnagram("Shashwat", "Shawatsh"));
System.out.println(testAnagram("Shashwat", "Shawatwh"));
System.out.println(testAnagramWithInbuiltMethods("Shashwat", "Shawatsh"));
System.out.println(testAnagramWithInbuiltMethods("Shashwat", "Shawatwh"));
}
private static boolean testAnagramWithInbuiltMethods(String str1, String str2) {
char[] charArray1 = str1.toCharArray();
char[] charArray2 = str2.toCharArray();
Arrays.sort(charArray1);
Arrays.sort(charArray2);
return Arrays.equals(charArray1, charArray2);
}
private static boolean testAnagram(String str1, String str2) {
if (str1.length() != str2.length()) {
return false;
}
char[] charArray = str1.toCharArray();
for (char ch : charArray) {
int index = str2.indexOf(ch);
if (index != -1) {
str2 = str2.substring(0, index) + str2.substring(index + 1, str2.length());
} else {
return false;
}
}
return str2.isEmpty();
}
}
Comments
Post a Comment