[leetcode#49] Group anagrams

Source: Internet
Author: User

problem:

Given an array of strings, group anagrams together.

For example, given: ["eat", "tea", "tan", "ate", "nat", "bat"] ,
Return:

["  ate", "eat", "tea"],  ["Nat", "Tan"],  ["bat"]]

Note:

    1. For the return value, each inner list ' s elements must follow the lexicographic order.
    2. All inputs'll is in lower-case.

Wrong solution 1:

 Public classSolution { PublicList<list<string>>groupanagrams (string[] strs) {if(STRs = =NULL)            Throw NewIllegalArgumentException ("STRs is null"); List<List<String>> ret =NewArraylist<list<string>> (); if(Strs.length = = 0) {Ret.add (NewArraylist<string> ()); returnret; } Comparator<String> Comp =NewComparator<string>() {@Override Public intCompare (String str1, String str2) {returnStr1.compareto (STR2);        }        };        Arrays.sort (STRs, comp); HashMap<string, arraylist<string>> map =NewHashmap<string, arraylist<string>> ();  for(String str:strs) {string Sorted_str=sortstr (str); if(Map.containskey (sorted_str)) {Map.get (SORTED_STR). Add (str); } Else{ArrayList<String> item =NewArraylist<string> ();                Item.add (str);            Map.put (Sorted_str, item); }        }        returnret; }            Privatestring Sortstr (String str) {Char[] Char_array =Str.tochararray ();        Arrays.sort (Char_array); returnchar_array.tostring (); }}

MistakesAnalysis:

mistake:input:[""]output:[]expected:[[""]]analysis:1. Misunderstood "" withNULL. "is also accounted as a string, it just has no character. But the string "had a reference forit. [""] is a String array with only one element, the element is ""string. We must tackle it as a valid input. And there is a stupid the bug in above solution. Not because the ability to handle""string. the""would work a valid string to go through all the code. The problem forAbove solution is:i forget to add the newly created arraylist<string> into RET set!!! -----------------------------------------------------------ArrayList<String> item =NewArraylist<string>(); Item.add (str); Map.put (sorted_str, item); Fix:arraylist<String> item =NewArraylist<string>(); Item.add (str); Ret.add (item); Map.put (SORTED_STR, item) ;-----------------------------------------------------------2. There is also a block of extra code. The Arrays.sort () function acutally could handle the sort among strings, no need to implement any extra comparator. Sort (object[] a) sorts the specified array of objects into ascending order, according to the natural ordering of its elemen Ts.------------------------------------------------------------------------------http://docs.oracle.com/javase/7/docs/api/java/lang/comparable.htmlThe natural ordering means the CompareTo method defined in theclass.------------------------------------------------------------------------------compareTo (String anotherstring) compares, strings lexicographically.

Wrong Solution 2:

 Public classSolution { PublicList<list<string>>groupanagrams (string[] strs) {if(STRs = =NULL)            Throw NewIllegalArgumentException ("STRs is null"); List<List<String>> ret =NewArraylist<list<string>> (); if(Strs.length = = 0) {ArrayList temp=NewArraylist<string> (); returnret;        } arrays.sort (STRs); HashMap<string, arraylist<string>> map =NewHashmap<string, arraylist<string>> ();  for(String str:strs) {string Sorted_str=sortstr (str); if(Map.containskey (sorted_str)) {Map.get (SORTED_STR). Add (str); } Else{ArrayList<String> item =NewArraylist<string> ();                Item.add (str);                Ret.add (item);            Map.put (Sorted_str, item); }        }        returnret; }        Privatestring Sortstr (String str) {Char[] Char_array =Str.tochararray ();        Arrays.sort (Char_array); returnchar_array.tostring (); }}

MistakesAnalysis:

mistakes:input:["", ""]output:[[""],[""]]expected:[["", ""Char   Char[].tostring (), it returns the array ' s reference in String form, like: [[email protected]CH Arnew  String. return New String (Char_array);

Solution:

 Public classSolution { PublicList<list<string>>groupanagrams (string[] strs) {if(STRs = =NULL)            Throw NewIllegalArgumentException ("STRs is null"); List<List<String>> ret =NewArraylist<list<string>> (); if(Strs.length = = 0)             returnret;        Arrays.sort (STRs); HashMap<string, arraylist<string>> map =NewHashmap<string, arraylist<string>> ();  for(String str:strs) {string Sorted_str=sortstr (str); if(Map.containskey (sorted_str)) {Map.get (SORTED_STR). Add (str); } Else{ArrayList<String> item =NewArraylist<string> ();                Item.add (str);                Ret.add (item);            Map.put (Sorted_str, item); }        }        returnret; }        Privatestring Sortstr (String str) {Char[] Char_array =Str.tochararray ();        Arrays.sort (Char_array); return NewString (Char_array); }}

[leetcode#49] Group anagrams

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.