字符串全排序问题(String Permutations)

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)

参考:http://hi.baidu.com/wibrst/item/fa4a9fa04f87663c030a4de5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值