问题描述
“变位词”是指两个词之间存在组成字母的 重新排列关系 如:heart和earth,python和typhon 为了简单起见,假设参与判断的两个词仅由小写 字母构成,而且长度相等(Python实现)
解法1:逐字检查
将词1中的字符逐个到词2中检查是否存在,存在就打勾标记(防止重复检查),如果每个字符都能找到,则两个词是变位词,只要有一个字符找不到,就不是变位词
def anagramSolution(s1, s2):
alist = list(s2)
pos1 = 0
stilOK = True
while pos1 < len(s1) and stilOK:
pos2 = 0
found = False
while pos2 < len(alist) and not found:
if s1[pos1] == alist[pos2]:
found = True
else:
pos2 += 1
if found:
alist[pos2] = None
else:
stilOK = False
pos1 = pos1 + 1
return stilOK
print(anagramSolution('python', 'thonay'))
复制代码
解法2:排序比较
解题思路:将字符串改成列表,对比两个列表中的每一位字符是否相等
def anagramSolution2(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(anagramSolution2('python', 'thonay'))
复制代码
解法3:计数比较
解题思路:对比两个词中每个字母出现的 次数,如果26个字母出现的次数都相同的话,这两个字符串就一定是变位词
def anagramSolution3(s1, s2):
c1 = [0] * 26
c2 = [0] * 26
for i in range(len(s1)):
pos = ord(s1[i])-ord('a')
c1[pos] = c1[pos] + 1
for i in range(len(s2)):
pos = ord(s2[i])-ord('a')
c2[pos] = c2[pos] + 1
j = 0
stilOk = True
while j < 26 and stilOk:
if c1[j] == c2[j]:
j = j + 1
else:
stilOk = False
return stilOk
复制代码
大家可以看下这三种方式,分别的时间复杂度是多少?
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END