Description:
Write a program to print out all the permutations of a string in alphabetical order.
Input sample:
The first argument will be a text file containing an input string, one per line. e.g.
hat
Output sample:
Print to stdout, permutations of the string, comma separated, in alphabetical order.
e.g.
aht,ath,hat,hta,tah,tha
解决方案:
import sys
#字符串可以看做是前缀(head)和后缀(tail)的连接
def str_perm(string):
n = len(string)
#当字符串长度为1时仅有一种前缀方案
if n == 1:
return [string]
#result是以string中的每个字母为前缀的所有字符串集合
result = []
for i in range(n):
#字符串中每一个字母均可充当前缀
head = string[i]
#sExcHead 表示除去前缀字母后的新字符串
sExcHead = string[:i] + string[i+1:]
#递归求出sExcHead 包含集中前缀方案,并将其作为相对于head而言的后缀,即vcTail
vcTail = str_perm(sExcHead)
for t in vcTail:
result.append(head+t)
return result
if __name__ == "__main__":
argv = sys.argv
inf = open(argv[1],'r')
while True:
line = inf.readline()
if len(line) == 0:
break
line = line.replace('\n','')
result = str_perm(line)
result.sort()
print ','.join(result)