字符串的全排列

Posted veli

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串的全排列相关的知识,希望对你有一定的参考价值。

假定字符串S,以字符序列a1a2...an表示。例如: 对于字符串"abc", 全排列为cba bca bac cab acb abc

本文采用非递归方法分别给出Python版实现和C代码实现。

 1 #!/usr/bin/python
 2 import sys
 3 
 4 def str2listuniq(s):
 5     l = []
 6     for c in list(s):
 7         if c not in l:
 8             l.append(c)
 9     return l
10 
11 def insert_c2s(s, c):
12     l = []
13     i = 0
14     while i <= len(s):
15         start = s[0:i]
16         end   = s[i:]
17         e     = start + c + end
18         l.append(e)
19         i += 1
20     return l
21 
22 def list2allperms(l):
23     l_final = [l[0]]
24     for c in l[1:]:
25         l_cell = []
26         for s in l_final:
27             l_cell.extend(insert_c2s(s, c))
28         l_final = l_cell
29     return l_final
30 
31 def main(argc, argv):
32     if argc != 2:
33         sys.stderr.write("Usage: %s <string>\n" % argv[0])
34         sys.stderr.write(" e.g.: %s \"abc\"\n" % argv[0])
35         return -1
36 
37     if len(argv[1]) == 0:
38         sys.stderr.write("Oops, string is blank\n")
39         return -1
40 
41     l_input = str2listuniq(argv[1])
42     l_final = list2allperms(l_input)
43     if len(l_final) <= 24:
44         print  .join(l_final)
45     else:
46         print  .join(l_final[0:5]) + " ... " + l_final[-1]
47     print "\nThe total number of all permutation is %d" % len(l_final)
48 
49     return 0
50 
51 if __name__ == __main__:
52     argc, argv = len(sys.argv), sys.argv
53     sys.exit(main(argc, argv))

测试结果:

$ ./foo.py a
a

The total number of all permutation is 1

$ ./foo.py ab
ba ab

The total number of all permutation is 2

$ ./foo.py abc
cba bca bac cab acb abc

The total number of all permutation is 6

$ ./foo.py abcd
dcba cdba cbda cbad dbca bdca bcda bcad dbac bdac badc bacd dcab cdab cadb cabd dacb adcb acdb acbd dabc adbc abdc abcd

The total number of all permutation is 24

$ ./foo.py abcde
edcba decba dceba dcbea dcbae ... abcde

The total number of all permutation is 120

用C代码实现比较复杂一些,因为要构造动态数组,wait for a while ...

以上是关于字符串的全排列的主要内容,如果未能解决你的问题,请参考以下文章

递归 - 求数字/字符串的全排列

字符串的全排列

算法——全排列

算法习题---字符串的全排序列

js-FCC算法-No repeats please字符串的全排列

字符串的全排列