LC打怪录 anagram difference

an anagram is a word whose characters can be rearranged to create another word.

given two strings, determine the min. number of characters in either string thatmust be modified to make the two strings anagrams. if it is not possible to make the two strings anagrams, return -1.

example:

a = ['tea','tea','act']

b=['ate','toe','acts']

a[0] = tea and b[0]= ate are anagrams, so 0 characters need to be modified.

a[1]=tea and b[1] = toe are not anagrams. modify 1 character in either string (o -> a or a -> o) to make them anagrams.

Function description:

complete the function getMinimumDifference in the editor below

getMinimumDifference has the following parameters:

string a[n]:an array of strings

string b[n]:an array of strings

Return

int[n]: the minimum number of characters in either string that needs to be modified to make the two strings anagrams pr-1 if it is not possible. 

Constraints

  • each string consists of a lower characters [a-z]
  • 1<= n<=100
  • 0<= |a[i],b[i]|<=10^4

242. 有效的字母异位词

49. 字母异位词分组

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        table = {}
        for s in strs:
            s_ = "".join(sorted(s))
            if s_ not in table:
                table[s_] = [s]
            else:
                table[s_].append(s)
        return list(table.values())
  1. class Solution: 定义了一个名为 Solution 的类。

  2. def groupAnagrams(self, strs: List[str]) -> List[List[str]]: 定义了 Solution 类中的一个方法 groupAnagrams。这个方法接受一个参数 strs,它是一个字符串列表 (List[str])。这个方法的返回值是一个列表的列表 (List[List[str]]),其中每个子列表包含了一组字谜。

  3. table = {} 初始化一个空字典 table。这个字典将用于存储字谜组。字典的键将是字符串的一个排序后的版本,而值将是原始字符串的列表,这些原始字符串排序后与键相同。

  4. for s in strs: 遍历输入的字符串列表 strs,每次循环中的 s 代表列表中的一个字符串。

  5. s_ = "".join(sorted(s)) 首先对字符串 s 中的字符进行排序,然后用 "".join() 将排序后的字符列表连接成一个新的字符串。这个新字符串 s_s 的字符的一个有序排列,将用作字典 table 的键。

  6. if s_ not in table: 检查排序后的字符串 s_ 是否不在字典 table 的键中。

  7. table[s_] = [s] 如果 s_ 不在字典的键中,将 s_ 添加到字典中,并将其值设置为一个列表,该列表仅包含当前字符串 s。这表示找到了一个新的字谜组。

  8. else: 如果排序后的字符串 s_ 已经在字典的键中,则表示当前字符串 s 是已存在字谜组的一部分。

  9. table[s_].append(s) 将当前字符串 s 添加到与排序后的字符串 s_ 对应的列表中。这样,所有字谜都会被分组到同一个列表中。

  10. return list(table.values()) 最后,方法返回字典 table 的所有值的列表。每个值是一个列表,包含了一组字谜。这样,所有的字谜组都被作为子列表返回,形成一个列表的列表。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值