1、问题描述
所谓“变位词”是指两个词之间存在组成字母的重新排列关系
如: heart和earth,python和typhon
为了简单起见,假设参与判断的两个词仅由小写字母构成,而且长度相等
2、问题求解
- 方法1:遍历
将词1中的字符逐个到词2中检查是否存在存在就“打勾”标记 (防止重复检查)
如果每个字符都能找到,则两个词是变位词只要有1个字符找不到,就不是变位词
def anagramSolution1(s1,s2):
if len(s1) != len(s2):
return False
else:
alist = list(s2)
pos1 = 0
stillOK = True
while pos1 < len(s1) and stillOK:
pos2 = 0
found = False
while pos2 < len(alist) and not found:
if s1[pos1] == alist[pos2]:
found = True
else:
pos2 = pos2 + 1
if found:
alist[pos2] = None
else:
stillOK = False
pos1 = pos1 + 1
return stillOK
- 方法2:排序法
将词1和词2转成列表类型,对列表进行排序,对比
def anagramSolution2(s1,s2):
s1_list = list(s1)
s2_list = list(s2)
s1_list.sort()
s2_list.sort()
if s1_list == s2_list:
return True
else:
return False
- 方法3:暴力求解
排列词1的所有字母排序的可能情况与词2对比,这里使用递归的思想进行随机排列
def anagramSolution3(s1,s2):
def perm(s):
""""递归求解字符串排列所有可能结果"""
if len(s)<=1:
return [s]
sl=[]
for i in range(len(s)):
for j in perm(s[0:i]+s[i+1:]):
sl.append(s[i]+j)
return sl
if len(s1) != len(s2):
return False
else:
sl = perm(s1)
if s2 in sl:
return True
else:
return False
- 方法4:计数比较
def anagramSolution4(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
stillOK = True
while j < 26 and stillOK:
if c1[j] == c2[j]:
j = j + 1
else:
stillOK = False
retrun stillOK