LeetCode: Group Anagrams

Source: Internet
Author: User

LeetCode: Group Anagrams

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:
For the return value, each inner list's elements must follow the lexicographic order.
All inputs will be in lower-case.

Find the sequence of words in the given string array that can form different alphabetic orders. For details, refer to the example.

Solution: strings that match the meaning of the question can be sorted by letters in the same order. Therefore, we only need to use HashMap to store the corresponding sequence and the matching string.

Code:

public class Solution {    public List
  
    anagrams(String[] strs) {        Map
   
     pairs = new HashMap
    
     ();        List
     
       result = new LinkedList
      
       (); Map
       
         remain = new HashMap
        
         (); for (String s:strs) { char[] key = s.toCharArray(); Arrays.sort(key); if (key.length == 0) key = null; String k = key != null ? new String(key) : null; String pair = pairs.put(k, s); if (pair != null) { result.add(pair); remain.put(k, s); } } result.addAll(remain.values()); return result; }}
        
       
      
     
    
   
  

 

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.