Leetcode-group anagrams

Source: Internet
Author: User

Given an array of strings, group anagrams together.

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

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


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

The mapping relationship is as follows:

The code is as follows:

Package Leetcode;
Import java.util.*;
Import Java.util.Map.Entry;
Idea: Set up a map mapping relationship, first the string is ordered as a key, and then map value mapping to the list inside ~
List's Advantages: variable!
public class Groupanagrams {
Public list<list<string>> groupanagrams (string[] strs) {
list<list<string>> ans = new arraylist<> ();
map<string, list<string>> map = new hashmap<> ();

for (String str:strs) {
Char[] ers = Str.tochararray ();
Arrays.sort (ERS);
String keystr = string.valueof (ers);
if (!map.containskey (KEYSTR))
Map.put (Keystr, New arraylist<> ()); Value is the new list and then joins the original STR
Map.get (KEYSTR). Add (str); If it is not a new list, join STR directly
For (entry<string, list<string>> entry:map.entrySet ()) {//map Entry is a set, not duplicated because different entry,hashcode does not With
Ensure its uniqueness
list<string> newvalues = Entry.getvalue ();
Collections.sort (NewValues); Here, the key of map is a set, and value is a list, so it can be sorted;
Ans.add (NewValues);
return ans;


Leetcode-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.