变位词是指由相同字母重新排列而成的单词。解决变位词算法问题的常见方法是使用哈希表。
以下是一个用哈希表解决变位词算法问题的示例代码:
def is_anagram(word1, word2):
# 创建两个哈希表,用于统计每个字母出现的次数
count1 = {}
count2 = {}
# 统计word1中每个字母出现的次数
for char in word1:
count1[char] = count1.get(char, 0) + 1
# 统计word2中每个字母出现的次数
for char in word2:
count2[char] = count2.get(char, 0) + 1
# 比较两个哈希表是否相同
return count1 == count2
# 测试代码
print(is_anagram("listen", "silent")) # True
print(is_anagram("hello", "world")) # False
以上代码中,我们使用两个哈希表count1
和count2
分别统计了两个单词中每个字母出现的次数。最后比较两个哈希表是否相同,如果相同则说明是变位词。
这种方法的时间复杂度为O(n),其中n为两个单词中字符的总数。