美文网首页
LeetCode 49. 字母异位词分组

LeetCode 49. 字母异位词分组

作者: _LT | 来源:发表于2019-05-09 10:29 被阅读0次

    LeetCode 49. 字母异位词分组

    1、题目链接

    https://leetcode-cn.com/problems/group-anagrams/

    2、解题思路

    将26个字母依次赋予对应的质数为别名,乘积相等则字母必然为同一组。目前实现速度较慢,但内存使用较低

    3、代码

    ```

    private val letterAlias =

            intArrayOf(2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41,

                43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101)

        fun groupAnagrams(strs: Array<String>): List<List<String>> {

            val result = arrayListOf<MutableList<String>>()

            val cacheIndex = hashMapOf<Long, Int>()

            var product : Long

            strs.forEach {

                product = 1

                it.forEach {

                    product *= letterAlias[it - 'a'] ?: 1

                }

                val has = cacheIndex.containsKey(product)

                if (!has) {

                    result.add(arrayListOf(it))

                    cacheIndex[product] =result.size -1

                } else {

                    result[cacheIndex[product]!!].add(it)

                }

                Unit

            }

            return result

        }

    ```

    4.提交记录

    相关文章

      网友评论

          本文标题:LeetCode 49. 字母异位词分组

          本文链接:https://www.haomeiwen.com/subject/gmbioqtx.html