Problem
Calc if two strings are anagrams. For example:
hello and elloh are anagrams
helo and hello are not anagrams
Solution
1. Sort the elements in the lists
2. Compare if two lists are equal
import java.util.*;
public class Anagrams{
public static void main(String[] arguments){
char[] firstString = "hello".toCharArray();
char[] secondString = "elhlo".toCharArray();
System.out.print(Anagrams.IsAnagrams(firstString, secondString));
}
public static boolean IsAnagrams(char[] firstString, char[] secondString){
ArrayList<Character> firstList = new ArrayList<Character>();
for(char c: firstString){
firstList.add(c);
}
ArrayList<Character> secondList = new ArrayList<Character>();
for(char c: secondString){
secondList.add(c);
}
Collections.sort(firstList);
Collections.sort(secondList);
return firstList.equals(secondList);
}
}
Output
true