声明:参考B站视频,自学成长记录
https://www.bilibili.com/video/BV1VC4y1x7uv?from=search&seid=12619305018182705301
计数比较方式实现变位词判断
'''
需求:
比较两个字符串是否为变位词
计数比较方式解题思路:
对比两个词中每个字母出现的次数
如果26个字母出现的次数都相同
则两个字符串一定是变位词
'''
def count_comparison(s1, s2):
c1 = [0] * 26
c2 = [0] * 26
for i in range(len(s1)): # i = 0
pos = ord(s1[i]) - ord('a') # s1[i] = c
# print(pos) # 2 表示该字母与a的位置差
# print(c1[pos]) # 计数初始为0
c1[pos] = c1[pos] + 1 # 字母对应在列表位置,对应的值 + 1
# print(c1[pos]) # 1 表示该字母匹配到的次数
for i in range(len(s2)):
pos = ord(s2[i]) - ord('a')
c2[pos] = c2[pos] + 1
# 遍历两个列表,相同下标下的次数是否相当
j = 0
check = True
while j < 26 and check:
if c1[j] == c2[j]:
j = j + 1
else:
check = False
return check
print(count_comparison("china", 'inach')) # True