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
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())
-
class Solution:
定义了一个名为Solution
的类。 -
def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
定义了Solution
类中的一个方法groupAnagrams
。这个方法接受一个参数strs
,它是一个字符串列表 (List[str]
)。这个方法的返回值是一个列表的列表 (List[List[str]]
),其中每个子列表包含了一组字谜。 -
table = {}
初始化一个空字典table
。这个字典将用于存储字谜组。字典的键将是字符串的一个排序后的版本,而值将是原始字符串的列表,这些原始字符串排序后与键相同。 -
for s in strs:
遍历输入的字符串列表strs
,每次循环中的s
代表列表中的一个字符串。 -
s_ = "".join(sorted(s))
首先对字符串s
中的字符进行排序,然后用"".join()
将排序后的字符列表连接成一个新的字符串。这个新字符串s_
是s
的字符的一个有序排列,将用作字典table
的键。 -
if s_ not in table:
检查排序后的字符串s_
是否不在字典table
的键中。 -
table[s_] = [s]
如果s_
不在字典的键中,将s_
添加到字典中,并将其值设置为一个列表,该列表仅包含当前字符串s
。这表示找到了一个新的字谜组。 -
else:
如果排序后的字符串s_
已经在字典的键中,则表示当前字符串s
是已存在字谜组的一部分。 -
table[s_].append(s)
将当前字符串s
添加到与排序后的字符串s_
对应的列表中。这样,所有字谜都会被分组到同一个列表中。 -
return list(table.values())
最后,方法返回字典table
的所有值的列表。每个值是一个列表,包含了一组字谜。这样,所有的字谜组都被作为子列表返回,形成一个列表的列表。