题目:输入一个字符串,按字典序打印出该字符串中字符的所有排列。例如输入字符串abc,则按字典序打印出由字符a,b,c所能排列出来的所有字符串abc,acb,bac,bca,cab和cba。
思路:字典序即该字符串的下个字符串保持尽可能长的前缀,并且下个字符串是拥有共同前缀的所有字符串中最小的;从右往左看,当遇到第一个降序的位置记为i-1,如123698754,从右往左看,在6出现的位置出现第一个降序,将6与i及之后的位置中最后一个比6大的数进行交换,在这个字符串中即是7, 将67 调换之后即得到123798654,将i之后的所有数字倒序,即得到123745689,即是123698754的按照字典序的下一个字符串。
code:
class Solution:
def __init__(self):
self.all = []
def Permutation(self, ss):
# write code here
# ss = list(ss)
self.all.append(ss)
next_ss = True
while next_ss:
nextss = list(ss)
for i in range(len(nextss)-1, 0, -1):
if nextss[i-1] < nextss[i]:
# import pdb;pdb.set_trace()
for j in range(len(nextss)-1,i-1, -1):
if nextss[j] > nextss[i-1]:
nextss[i-1], nextss[j] = nextss[j], nextss[i-1]
nextss[i:] = nextss[i:][::-1]
break
break
nextss = ''.join(nextss)
# print(nextss)
# import pdb;pdb.set_trace()
if ss == nextss:
next_ss = False
else:
self.all.append(nextss)
ss = nextss
# print(self.all)
return self.all