LeetCode 49: ectopic letter word packet Group Anagrams

LeetCode 49: ectopic letter word packet Group Anagrams

topic:

Given a string array, ectopic word letters together. Ectopic word letters refer to the same letters, but arranged in different strings.

Given an array of strings, group anagrams together.

Example:

输入: ["eat", "tea", "tan", "ate", "nat", "bat"],
输出:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

Description:

  • All inputs are lowercase letters.
  • The order of the answers that were not considered.

Note:

  • All inputs will be in lowercase.
  • The order of your output does not matter.

Problem-solving ideas:

Whatever the subject of the request is the same as the property of the letters in alphabetical order as long as a class, as long as all the words in alphabetical order according to certain rules of good, as long as the same string of letters in each word line up according to the law, it is classified as a class

Sort letters problem solving:

A hash map {Key : Value}Key string is sorted, Value array, storing the same letter Key words, and each word traversing sorted letters, to find out whether the sorted strings are present in Keys, may use a hash map the seek operation time reduced complexity O (1)

Which solving logic (in ascending alphabetical herein):

输入: ["eat", "tea", "tan", "ate", "nat", "bat"]
建立哈希映射 map = {}
遍历该字符串数组:

第一个单词: "eat" --> "aet"
"aet" 不存在于 map, 建立映射 {"aet" : [ "eat" ] }

第二个单词: "tea" --> "aet"
"aet" 存在于 map, 加入其 Values {"aet" : [ "eat" , "tea" ] }

第三个单词: "tan" --> "ant"
"ant" 不存在于 map, 建立映射  {"aet" : [ "eat" , "tea" ] ; "ant" : [ "tan" ] }

第四个单词: "ate" --> "aet"
"aet" 存在于 map, 加入其 Values {"aet" : [ "eat" , "tea" , "ate" ] ; "ant" : [ "tan" ] }

......

map = {"aet" : [ "eat" , "tea" , "ate" ] ; "ant" : [ "tan" , "nat"] ; "abt" : [ "bat" ] }

返回该哈希映射的 Values 组成的数组:
[
  ["ate","eat","tea"],
  ["nat","tan"],
  ["bat"]
]

the complexity:

  • Time complexity: O (N * (K * logK)), where N is the length of strs, and K is the maximum length of the string strs. Traversing each string complexity of O (N). Sort function using the built-in letter sorting string time complexity is O (K * logK).

  • Space complexity: O (N * K), in the map data storage space occupied.

Problem-solving word frequency statistics:

This problem-solving method may also re-optimized operation of the string collation may be omitted.

Think about it, a word of up to 26 English letters, you can not establish it as a hash map?:

对于单词 "aeat" :
建立哈希映射{ 'a' : 2 ; 'e' : 1; t : 1 }

as a key word appears, value appearing frequency. If you go through each key to determine whether the same letter, and then determine whether the same number of occurrences, which is obviously more complicated.

The frequency of appearance of each letter can be composed of consecutive characters:

每个字母 a-z 出现频次: [2,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0]
组成字符串: "20001000000000000001000000"

Simply determine whether the frequency of each word letter strings are the same times on it.

You can also ask for word frequency optimization, the number of fixed 26 letter, establish a direct array of length 26, 26 letters on behalf of its index position, traversing the word of the letters, each letter appears once the letter on behalf of elements in the array value plus 1.

This avoids the sort operation

Sort letters problem solving:

Java:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if(strs.length==0) return new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();//建立映射关系
        for (String s : strs) {//遍历该字符串数组
            char[] chs = s.toCharArray();//转成字符
            Arrays.sort(chs);//排序字符串字母
            String key = String.valueOf(chs);//转成字符串
            if(!map.containsKey(key)) map.put(key, new ArrayList<>());//如果 key 不存在, 新建映射关系
            map.get(key).add(s);//加入其对应的 Value 所在的数组
        }
        return new ArrayList(map.values());//返回 Values 组成的数组
    }
}

Python:

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        ans = collections.defaultdict(list) # 建立映射关系
        for s in strs: # 遍历该字符串数组
            ans[tuple(sorted(s))].append(s) # sorted(s):排序字符串字母, 并加入其对应的 Value 所在的数组
        return ans.values() # 返回 Values 组成的数组

Problem-solving word frequency statistics:

Java:

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList<>();
        Map<String, List<String>> map = new HashMap<>();// 建立映射关系
        for (String s : strs) {//遍历该字符串数组
            int[] count = new int[26];//建立一个 26 字母的映射关系
            for (char c : s.toCharArray()) count[c - 'a']++;//遍历字字符串每个字母统计每个字母出现的频次
            String key = Arrays.toString(count);//转成字符串
            if (!map.containsKey(key)) map.put(key, new ArrayList<>());//如果 key 不存在, 新建映射关系
            map.get(key).add(s);//加入其对应的 Value 所在的数组
        }
        return new ArrayList(map.values());//返回 Values 组成的数组
    }
}

Python:

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        ans = collections.defaultdict(list)# 建立映射关系
        for s in strs: # 遍历该字符串数组
            count = [0] * 26 # 建立一个 26 字母的映射关系
            for c in s: # 遍历字字符串每个字母
                count[ord(c) - 97] += 1 # 每个字母出现的频次(元素值)加1
            ans[tuple(count)].append(s) # 加入其对应的 Value 所在的数组
        return ans.values() # 返回 Values 组成的数组

Welcome attention to micro-channel public number: Write Love Bug

I love to write Bug.png

Guess you like

Origin www.cnblogs.com/zhangzhe532/p/12003780.html