Given an array of strings, return all groups of strings that is anagrams.
Note:all inputs'll is in lower-case.
Test instructions, is to determine whether there is a palindrome string in the character array (determine whether two strings are composed of the same letter, but the order may be different).
How to solve the problem: the first thought is to rearrange the characters in the array in alphabetical order. Then use the map to store the string as the key value, using a list linked list to record the string before sorting the index in the array. Then the length of the list is interpreted, and the description greater than 1 is a return character, added to list.
Public list<string> anagrams (string[] strs) {list<string> list=new arraylist<string> (); int len=strs.length; if (len<=1) return list; Map<string,list<integer>> map=new hashmap<string,list<integer>> (); String Str=null; StringBuffer buffer=new StringBuffer (); for (int i=0;i<len;i++) {str=strs[i]; Char[] Chars=str.tochararray (); Arrays.sort (chars); for (char ch:chars) {buffer.append (CH); } str=buffer.tostring (); Buffer.delete (0,str.length ()); if (Map.get (str) ==null) {list<integer> tmplist=new arraylist<integer> (); Tmplist.add (i); Map.put (str, tmplist); } else {map.get (str). Add (i); }} set<string> Keyset=map.keyset (); for (Iterator<string> Iter=keyset.iterator (); Iter.hasnext ();) {String keystr=iter.next (); List<integer> Listindex=map.get (KEYSTR); Len=listindex.size (); if (len<=1) continue; for (int i=0;i<len;i++) {List.add (Strs[listindex.get (i)]); }} return list; }The running time is longer, 766ms. Can you optimize it. Stored directly at the time of judgment.
Public list<string> anagrams (string[] strs) { list<string> list=new arraylist<string> (); int len=strs.length; if (len<=1) return list; Map<string,integer> map=new hashmap<string,integer> (); String Str=null; for (int i=0;i<len;i++) { str=strs[i]; Char[] Chars=str.tochararray (); Arrays.sort (chars); Str=new String (chars); if (Map.containskey (str))//Determine if the map has a re-arranged str { int index=map.get (str); if (index!=-1)//Determine if the second time exists the same key. If yes, the array value corresponding to the first index is taken out into list { list.add (Strs[index]); Map.put (str,-1); } List.add (Strs[i]); } else { map.put (str,i); } } return list; }
[Java] LeetCode49 anagrams