当前位置:网站首页>Leetcode 49 letter heterotopic word grouping

Leetcode 49 letter heterotopic word grouping

2020-11-09 19:33:00 Want to exchange steamed stuffed bun for thesis

LeetCode49 Letter heterotopic word grouping

Title Description

Given an array of strings , Combine words with different letters . Letter heterotopia refers to the same letter , But arrange different strings .

Examples

 Input : ["eat", "tea", "tan", "ate", "nat", "bat"]
 Output :
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Algorithm analysis

  • After ordering , As key, use hashmap Storage
  • Traverse hash Of values, Join in ans that will do

Time complexity

\(O(nLlong(L))\)

Java Code

class Solution {
    
    public List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String,List<String>> map = new HashMap<String,List<String>>();
        int n = strs.length;
        for(int i = 0; i < n; i++){
            char[] c = strs[i].toCharArray();
            Arrays.sort(c);
            String s = new String(c);
            if(!map.containsKey(s)){
                map.put(s, new ArrayList<String>());
            }
            map.get(s).add(strs[i]);

        }

        List<List<String>> ans = new ArrayList<List<String>>();

        for(List<String> t : map.values()){
            ans.add(t);
        }

        return ans;
    }
}

版权声明
本文为[Want to exchange steamed stuffed bun for thesis]所创,转载请带上原文链接,感谢