Problem
Given an array of strings sort it such that the anagrams come side by side. A word is called anagram of another word, if one can be formed by rearranging the letters of the other, without any addition or deletion of letters.
Solution
As two anagrams have exact same set of letters and same count of letters, if we sort the letters of two anagrams they will be exactly the same. Now if we use this sorted sequence of a word as its comparison key in sorting, then basically two words having same sorted sequence will stay side by side. We use this technique to get this solution. We create a container class for the words and use the sorted sequence of that word as comparator of that class. Now we sort the array of containers. Then from the sorted containers we recreate the array of strings in the same order.
Code
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; public class AnagramSort { public static void main(String[] args) { String[]arr={"dog","listen","tip","enlist","pit","god","man","top","pot"}; sort(arr); for(String str:arr) { System.out.println(str); } } private static void sort(String[] arr) { Listlist=new ArrayList (); for(String str:arr) { list.add(new Anagram(str)); } Collections.sort(list); for(int i=0;i < arr.length;++i) { arr[i]=list.get(i).str; } } public static class Anagram implements Comparable { String str; public Anagram(String str) { this.str=str; } public String getSortedString() { char[]arr=str.toCharArray(); Arrays.sort(arr); return new String(arr); } @Override public int compareTo(Anagram o) { return getSortedString().compareTo(o.getSortedString()); } } }
No comments:
Post a Comment