首页 > 试题广场 >

字符串排列

[编程题]字符串排列
  • 热度指数:14075 时间限制:C/C++ 3秒,其他语言6秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解

给定一个字符串string A和其长度n,返回所有该字符串所包含字符的各种排列。要求输入字符串长度小于等于11且均为大写英文字符,排列中的字符串按字典序从大到小排序。(重复字符串不用合并)

测试样例:
"ABC"
返回:["CBA","CAB","BCA","BAC","ACB","ABC"]
我的这个python结果和答案一样啊,怎么不通过呢,有没有大佬
# -*- coding:utf-8 -*-
import itertools
class Permutation:
    # A是一个字符串
    def getPermutation(self, A):
        # write code here
        res = []
        if A == "": return []
        lit = list(itertools.permutations(list(A), len(A)))
        for elem in lit:
            x = ''.join(elem)
            if x not in res:
                res.append(x)
        res.sort(reverse=True)
        return res


发表于 2022-10-22 21:50:41 回复(1)

python solution:

from itertools import permutations
# -*- coding:utf-8 -*-
class Permutation:
    def getPermutation(self, A):

        return list(map(lambda c:"".join(c),sorted(permutations(A),reverse=True)))
发表于 2017-10-01 22:37:33 回复(0)
# -*- coding:utf-8 -*-
class Permutation:
    # A是一个字符串
    def getPermutation(self, A):
        # write code here
        self.vs=[]
        self.Permutatio(A,0)
        result=sorted(self.vs,reverse=True)
        return result
    def Permutatio(self,A,i):
        lena=len(A)
        #print lena
        if lena==i:
            self.vs.append(A)
        else:
            for j in range(i,lena):
                tmp=A[j]
                trailer=A[j+1:] if j+1<lena else ''
                A=A[0:j]+A[i]+trailer
                A=A[0:i]+tmp+A[i+1:]
                self.Permutatio(A, i+1)
                tmp=A[j]
                trailer=A[j+1:] if j+1<lena else ''
                A=A[0:j]+A[i]+trailer
                A=A[0:i]+tmp+A[i+1:]

发表于 2017-07-12 22:10:17 回复(0)

问题信息

难度:
3条回答 21006浏览

热门推荐

通过挑战的用户

查看代码