new

1.变位词

所谓"变位词"是指两个词之间存在组成字母的重新排列关系

如:heart和earth,python和typhon

为了简单起见,假设参与判断的两个词仅由小写字母构成,而且长度相等

思路1:建一个哈希表,将第一个单词中的字母存入到哈希表中。第二个单词的字母与哈希表对比,有一个相同的就从哈希表中取出一个,最后若哈希表为空则俩个单词相同。

def is_anagram(word1, word2):
  # 检查两个单词是否相等
  if len(word1) != len(word2):
    return False
    # 使用哈希表(字典)来存储第一个单词中每个字母出现的次数
  hash_table = {}
  for char in word1:
    if char in hash_table:
      hash_table[char] += 1
    else:
      hash_table[char] = 1
      # 遍历第二个单词,每遇到一个字母就在哈希表中减1
  for char in word2:
    if char in hash_table:
      hash_table[char] -= 1
      if hash_table[char] == 0:
        del hash_table[char]
    else:
      return False
      # 如果哈希表为空,则两个单词是变位词
  return len(hash_table) == 0

# 测试函数
print(is_anagram("heart", "earth"))  # 应该输出 True
print(is_anagram("word","droe")) #应该输出False

解法2:排序比较

将两个字符串都按照字母顺序排好序

再逐个字符对比是否相同,如果相同则是变位词,有任何不同就不是变位词

def anagrmSolution2(s1,s2):
  #转为列表
  alist1=list(s1)
  alist2=list(s2)
  #分别排序	
  alist1.sort()
  alist2.sort()
  pos=0
  matches=True
  while pos<len(s1) and matches:
    if alist1[pos] == alist2[pos]: #逐个对比
      pos=pos+1
    else:
      matches=False
  return matches
print(anagrmSolution2('cyf','cyx'))
posted @ 2024-08-21 23:31  无悔的选择  阅读(25)  评论(0)    收藏  举报