/**
* Function: Sort the array of strings and arrange all the inflection words in the adjacent position.
*/
Two methods:
Method One:
/** * idea: Apply sorting algorithm, and change the comparison device.Here the comparison device is used to indicate that two strings of Hu Wei conjugation are equal. * @param array */public static void sort (string[] array) {Arrays.sort (array, new Anagramcomparator ());} Class Anagramcomparator implements comparator<string>{@Override//Change the comparison device public int compare (String s1,s Tring S2) {return sortchars (S1). CompareTo (Sortchars (S2)); }/** * Idea: Check whether it is an inflection word. Sorts the strings directly. Assuming that each other is a modified word, the order is equal. * @param S * @return */public static String Sortchars (string s) {char[] Content=s.tochararray (); Arrays.sort (content); return new String (content); } }
Method Two:
/** * Idea: Use a hash table to store words that are the same as the inflection words, and then put them back in the array.* @param array */public static void Sort2 (string[] array) {hashmap<string,arraylist<string>> map=new HashMap <string, arraylist<string>> (); for (string s:array) {string Key=sortchars (s); if (Map.containskey (key)) { Arraylist<string> List=map.get (key); List.add (s);} Else{map.put (Key, New arraylist<string> ());}} Convert the HashMap to an array int index=0;for (string Key:map.keySet ()) {arraylist<string> list=map.get (key); for (String T: list) {array[index]=t;index++;}}} public static String Sortchars (string s) {char[] Content=s.tochararray (); Arrays.sort (content); return new String (content);}
9.11 Sort and find (ii)--sort the array of strings and arrange all the modifiers in the adjacent position