想法:
把未排序之前的最后一个元素依次跟未排序中的任意一个元素进行替换,但是替换完之后要检查是否存在这个元素,或者在最后把重复的元素都清除。
解题思路:
其实很简单,就是单纯的把字符串分成两段,一段是已经固定了的,就是已经遍历完所有可能性的字符串,第二段是还没固定的。
如图:它第一个字符的可能性只有‘e’和‘q’,把qeq和eqq保存了之后,第一位就算固定了。此时num_fixed=1.
class Solution:
#def
def permutation(self, S: str):
fixedList = [] # 用来保存已经确定的
unfixedList = [] # 用来保存下一次循环所需要用到的 上一层内容
unfixedList.append(S)
length = len(S) # 得到数据长度
# string = sorted(set(S)) #得到数据中所有字符的种类并且排序,比如:qeq 会得到eq
num_fixed = 0
while (num_fixed < length):
unlength = len(unfixedList)
for j in range(0, unlength):
str1 = unfixedList[j][0:num_fixed]
str2 = unfixedList[j][num_fixed:length]
string = sorted(set(str2))
#print(string)
for i in range(0, len(string)):
arg = str2.index(string[i])
result = str1 + str2[arg]
str3 = str2.replace(str2[arg], "",1)
result = result + str3
fixedList.append(result)
unfixedList.append(result)
del unfixedList[0:unlength]
num_fixed += 1
List = sorted(set(fixedList))
for i in range(0,len(List)):
List[i] = str(List[i])
return List
#print(fixedList)
a = Solution().permutation("qeq")
print(a)