Anagrams - LeetCode

56 篇文章 2 订阅
14 篇文章 1 订阅

Anagrams - LeetCode

题目:

Given an array of strings, return all groups of strings that are anagrams.

Note: All inputs will be in lower-case.


分析:

首先解释anagrams的含义:anagram解释为回文构词法,即单词里的字母的种类和数目没有改变,只是改变了字母的排列顺序。例如:eat ,eta ,tea 都是满足回文构词法的。
所以我们利用了两个hash表,首先把单词变成字母表顺序,dic是记录单词的出现位置,而count记录了单词的出现次数,因为如果出现两次单词,我们需要在最后加上最后一次出现的那个单词。

代码:

class Solution:
    # @param strs, a list of strings
    # @return a list of strings
    def anagrams(self, strs):
    
        dic = {}
        count = {}
        res = []
        for i in range(len(strs)):
            temp = "".join(sorted(strs[i]))
            if temp not in dic:
                dic[temp] = i
                count[temp] = 1
            else:
                res.append(strs[dic[temp]])
                dic[temp] = i
                count[temp] += 1
        for i in count.keys():
          if count[i] != 1:
              res.append(strs[dic[i]])
        return res


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值