Java for Leetcode 049 anagrams

Source: Internet
Author: User

Given an array of strings, return all groups of strings that is anagrams.

Note:all inputs'll is in lower-case.

Problem-solving ideas: First of all to understand, what is anagrams,ie. "Tea", "tae", "aet", and then very good to do, new a hashmap, using a sequence of string as key, repeated to add elements to the inside, there is a small episode, is the sort of time do not use Priorityqueue, Because Priorityqueue is sorted by heap, only the top element of the heap is guaranteed to be the highest priority (for a long time) the Java implementation is as follows:

static public list<string> anagrams (string[] strs) {list<string> List = new arraylist<string> (); Hashmap<string, list<string>> HM = new hashmap<string, list<string>> (); for (int i = 0; i < STRs . length; i++) {char [] c=strs[i].tochararray (); Arrays.sort (c); String Sortstring=new string (c), if (!hm.containskey (sortstring)) Hm.put (Sortstring.tostring (), New arraylist< String> ()); Hm.get (Sortstring.tostring ()). Add (Strs[i]);} iterator<string> Iterator = Hm.keyset (). Iterator (); while (Iterator.hasnext ()) {String key = Iterator.next (); if ( Hm.get (key). Size () > 1) list.addall (Hm.get (key));} return list;}

Java for Leetcode 049 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.