1. 程式人生 > >leetcode 784. 字母大小寫全排列(python)

leetcode 784. 字母大小寫全排列(python)

給定一個字串S,通過將字串S中的每個字母轉變大小寫,我們可以獲得一個新的字串。返回所有可能得到的字串集合。

示例:
輸入: S = "a1b2"
輸出: ["a1b2", "a1B2", "A1b2", "A1B2"]

輸入: S = "3z4"
輸出: ["3z4", "3Z4"]

輸入: S = "12345"
輸出: ["12345"]

注意:

  • S 的長度不超過12
  • S 僅由數字和字母組成。
class Solution(object):
    def spliteList(self, alist):
        flag = 0    # 判斷是否還含有兩個字母的元素
        for i in range(len(alist)):
            k = alist[i]
            if len(k) == 2:
                flag = 1
                list1 = alist[:i] + [k[0].lower()] + alist[i+1:]
                list2 = alist[:i] + [k[0].upper()] + alist[i+1:]
                break

        if flag == 0:
            return alist
        else:
            return list1, list2


    def letterCasePermutation(self, S):
        """
        :type S: str
        :rtype: List[str]
        """
        sList = list( S )
        letterNum = 0
        for i in range(len(S)):
            k = sList[i]
            if 'A'<= k <= 'z':
                letterNum += 1  # 統計一下字母的個數
                sList[i] = k.lower() + k.upper()

        allList = []
        allList.append( sList )

        while len( allList ) != 2**letterNum:
            l = len( allList )
            for i in range(l):
                list1 = allList[i]
                if len( list1 ) != len( ''.join(list1)):
                    del allList[i]
                    l1, l2 = self.spliteList( list1 )
                    allList.append( l1 )
                    allList.append( l2 )

        l = len( allList )
        for i in range(l):
            allList[i] = ''.join( allList[i] )

        return allList