Leetcode 784. Letter Case Permutation

就是枚举出所有情况:

class Solution:
    def letterCasePermutation(self, S):
        permutations = ['']

        for s in S:
            if s.isalpha():
                permutations = [p + letter for p in permutations for letter in
                                [s.lower(), s.upper()]]
            else:
                permutations = [p + s for p in permutations]

也可以使用itertools模块里面的笛卡尔积函数:

class Solution:
    def letterCasePermutation(self, S):
        L = [[i.lower(), i.upper()] if i.isalpha() else i for i in S]
        return [''.join(i) for i in itertools.product(*L)]

 

posted @ 2019-04-15 18:13  周洋  阅读(107)  评论(0编辑  收藏  举报