python三种方法检测变位词Anagram

本文阅读 1 分钟
首页 Python笔记 正文
  1. class AnagramDetection:
  2. # 先对两个字符串进行list化
  3. # 对字符串对应的两个list进行排序
  4. # 依次比较字符是否匹配
  5. def anagramSolution1(self, s1, s2):
  6. alist1 = list(s1)
  7. alist2 = list(s2)
  8. alist1.sort()
  9. alist2.sort()
  10. pos = 0
  11. matches = True
  12. while pos < len(s1) and matches:
  13. if alist1[pos] == alist2[pos]:
  14. pos = pos + 1
  15. else:
  16. matches = False
  17. return matches
  18. # 首先生成两个26个字母的list
  19. # 计算每个字母出现的次数并存入到相应的list中
  20. # 比较两个list是否相同
  21. def anagramSolution2(self, s1, s2):
  22. c1 = [0] * 26
  23. c2 = [0] * 26
  24. for i in range(len(s1)):
  25. pos = ord(s1[i]) - ord('a')
  26. c1[pos] = c1[pos] + 1
  27. for i in range(len(s2)):
  28. pos = ord(s2[i]) - ord('a')
  29. c2[pos] = c2[pos] + 1
  30. j = 0
  31. stillOK = True
  32. while j < 26 and stillOK:
  33. if c1[j] == c2[j]:
  34. j = j + 1
  35. else:
  36. stillOK = False
  37. return stillOK
  38. # 首先将两个字符串list化
  39. # 将两个list中的字符生成两个set
  40. # 比较两个set, 如果不相等直接返回false
  41. # 如果两个set相等, 比较每个set中字符在相应list中的个数, 个数不同返回false
  42. def anagramSolution3(self, s1, s2):
  43. alist1 = list(s1)
  44. alist2 = list(s2)
  45. aset1 = set(alist1)
  46. aset2 = set(alist2)
  47. if aset1 != aset2:
  48. return False
  49. else:
  50. for ch in aset1:
  51. if alist1.count(ch) != alist2.count(ch):
  52. return False
  53. return True
  54. s1 = 'abcde'
  55. s2 = 'acbde'
  56. test = AnagramDetection()
  57. print(test.anagramSolution1(s1, s2))
  58. print(test.anagramSolution2(s1, s2))
  59. print(test.anagramSolution3(s1, s2))
解压密码: detechn或detechn.com

免责声明

本站所有资源出自互联网收集整理,本站不参与制作,如果侵犯了您的合法权益,请联系本站我们会及时删除。

本站发布资源来源于互联网,可能存在水印或者引流等信息,请用户自行鉴别,做一个有主见和判断力的用户。

本站资源仅供研究、学习交流之用,若使用商业用途,请购买正版授权,否则产生的一切后果将由下载用户自行承担。

python平衡查找树AVL
« 上一篇 01-21
python二叉查找树
下一篇 » 01-21

发表评论