9.11 Sort and find (ii)--sort the array of strings and arrange all the modifiers in the adjacent position

Source: Internet
Author: User
Tags modifiers

/**
* 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 modify comparer. Here the comparator 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//Modify Comparator public int compare (String s1,s    Tring S2) {return sortchars (S1). CompareTo (Sortchars (S2)); }/** * Idea: Check whether it is an inflection word.     The strings are sorted directly, and if they are mutually modified, they are sorted equally.        * @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);}


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

9.11 Sort and find (ii)--sort the array of strings and arrange all the modifiers in the adjacent position

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.