Given one array of strings, you have to sort the array such that anagrams should occur together.
Below is my solution, can anyone tell me why this approach is not giving the correct answer.
class Solution {
public static void main(String[] args) {
String s[] = new String[]{"abc", "arp", "bac", "cba", "pra", "apr"};
Arrays.sort(s, new AnagramComparator());
System.out.println(Arrays.toString(s));
}
private static boolean isAnaGram(String s1, String s2) {
int freq[] = new int[26];
s1.chars().forEach(x -> freq[x - 'a']++);
s2.chars().forEach(x -> freq[x - 'a']--);
return Arrays
.stream(freq)
.allMatch(x -> x == 0);
}
static class AnagramComparator implements Comparator<String> {
@Override
public int compare(String s1, String s2) {
if (isAnaGram(s1, s2)) {
return 0;
}
return s1.compareTo(s2);
}
}
}