[LeetCode] [Java] Anagrams
Question:
Given an array of strings, return all groups of strings that are anagrams.
Note: All inputs will be in lower-case.
Question:
Given a string array, all multipart word combinations are returned.
Note: All input values are in lower case.
Algorithm analysis:
In fact, the inverted word structure is quite understandable, that is, the two words contain the same characters and numbers, but the order is different.
Sort the letters in a string, and the strings that are re-arranged are equal.
Based on the above ideas, a map is used to record the strings sorted by letters and their location (or original string). During traversal, if the sorted strings are equal, it means that the two are in the same order.
The first occurrence of the reordered string requires special care. In the following code, use-1 to identify whether the first occurrence of the reordered string has been added to the result.
In addition, you can sort strings alphabetically by the char array of the Java class library. You can also sort the string containing only lowercase letters.
AC code:
Public ArrayList
Anagrams (String [] strs) {ArrayList
List = new ArrayList
(); HashMap
Map = new HashMap
(); For (int I = 0; I <strs. length; ++ I) {char [] chars = strs [I]. toCharArray (); Arrays. sort (chars); String anort = new String (chars); if (map. containsKey (aney) {int index = map. get (ansible); if (index! =-1) {list. add (strs [index]); map. put (anager,-1); // use-1 to identify the first re-arranged string} list. add (strs [I]);} else map. put (ansible, I);} return list ;}