螞蟻金服筆試題加試——字符串的全排列(python版)

寫在前面

春招實習的簡歷被螞蟻金服的前輩撈起來了,有機會第二次筆試~感謝 考試時用java寫的,找了一下牛客網的鏈接重新寫了一哈
第一個題是字符串的全排列(劍指offer原題),第三個是求兩個排序數組的中位數。

題目描述

(牛客題目傳送門)
輸入一個字符串,按字典序打印出該字符串中字符的所有排列。例如輸入字符串abc,則打印出由字符a,b,c所能排列出來的所有字符串abc,acb,bac,bca,cab和cba。
輸入描述:
輸入一個字符串,長度不超過9(可能有字符重複),字符只包括大小寫字母。

常規解法

把大問題分爲小問題,把一個字符串看成兩部分。即abc=a+bc
然後分兩步,先求所有可能出現在第一個位置的字符(即把第一個字符和後面所有字符交換)
然後對後面那部分用同樣的方法遞歸求解。

常規解法的代碼

# -*- coding:utf-8 -*-
class Solution:
    def Permutation(self, ss):
        ans = []
        #嘗試第i個位置的所有可能
        def permutation(listx, i):
            if i == len(listx):
                ans.append(''.join(listx))
            else:
                for idx in range(i,len(ss)):
                    #把位置i的元素和他後面元素交換
                    t = listx[idx]
                    listx[idx] = listx[i]
                    listx[i] = t
                    permutation(listx, i+1);
                    #再換回來
                    t = listx[idx]
                    listx[idx] = listx[i]
                    listx[i] = t
        listx = list(ss)
        if listx is None or len(listx) == 0:
            return []
        permutation(listx,0)
        return sorted(set(ans))#注意需要排序

if __name__ == '__main__':
    Solution().Permutation("")

投機取巧版:萬能的python庫函數itertools.permutations

# -*- coding:utf-8 -*-
import itertools
class Solution:
    def Permutation(self, ss):
        # write code here
        if not ss:
            return []
        return sorted(list(set(map(''.join, itertools.permutations(ss)))))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章