我是编程新手,我写下了如下解决方案。我有什么方法可以为这个问题写出更好的解决方案吗?
def arePermutation(s1, s2):
if len(s1) != len(s2):
print 'length should be the same'
return
arr1 = []
arr2 = []
for i in range(len(s1)):
arr1.append(s1[i])
for i in range(len(s2)):
arr2.append(s2[i])
if set(arr1) == set(arr2):
print 'One string is permutaion of another'
else:
print 'Not permutation of another'
return
#arePermutation('rav', 'var')
#arePermutation('dog', 'ogd')
arePermutation('abcdeff', 'abcjklm')
答案 0 :(得分:2)
是的,因为此代码不起作用。尝试
arePermutation("aaab", "bbba")
相反,请列出每个字符串中的字符。对列表进行排序。如果列表相等,则字符串是彼此的排列(字谜)。
答案 1 :(得分:1)
你有一堆不必要的代码。另外,如果有重复的字符,您需要排序而不是表单集。没有理由将s1和s2复制到新列表arr1和arr2中,因为sorted()
将对字符串起作用,因为它是一个字符序列。此外,如果您没有返回值,那么最后不需要返回语句。所以这个更简单的代码工作正常:
def arePermutation(s1, s2):
if sorted(s1) == sorted(s2):
print 'One string is permutation of another'
else:
print 'Not permutation of another'
此外,通常最好让这种函数返回一个布尔值,然后在一个单独的函数中进行外部打印。