leetcode--784--字母大小写全排列

题目描述:

给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。

示例:

输入: S = "a1b2"
输出: ["a1b2", "a1B2", "A1b2", "A1B2"]

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

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

解题思路1:

来源: LeetCode

集合的笛卡尔乘积是从所有集合中选择每种可能的组合。例如 {1, 2 } x {a, b, c} = {1a, 1b, 1c, 2a, 2b, 2c}。

对于具有内置函数来计算笛卡尔积的语言,可以直接调用内置函数减少工作量。


代码1:

import itertools
class Solution(object):
    def letterCasePermutation(self, S):
        f = lambda x: (x.lower(), x.upper()) if x.isalpha() else x
        return map("".join, itertools.product(*map(f, S)))

s = Solution()
S = "a1b2c3"
print(list(s.letterCasePermutation(S)))

解题思路2:

来源于:minningl

递归的思想,结果等价于首字母拼接上 去除首字母的结果的值


代码2:

class Solution(object):
    def letterCasePermutation(self, S):

        if not S:
            return [S]
        ret = self.letterCasePermutation(S[1:])         
        if S[0].encode('utf-8').isdigit():            # isdigit()用来检测字符串是否只由数字组成
            return [S[0]+item for item in ret]      
        else:
            return [S[0].lower()+item for item in ret] + [S[0].upper()+item for item in ret]

s = Solution()
S = "a1b2c3"
print(s.letterCasePermutation(S))

解题思路3:

来源于:Leetcode

从左往右依次遍历字符,过程中保持 ans 为已遍历过字符的字母大小全排列。

例如,当 S = “abc” 时,考虑字母 “a”, “b”, “c”,初始令 ans = [""],依次更新 ans = [“a”, “A”], ans = [“ab”, “Ab”, “aB”, “AB”], ans = [“abc”, “Abc”, “aBc”, “ABc”, “abC”, “AbC”, “aBC”, “ABC”]。


代码3:

class Solution(object):
    def letterCasePermutation(self, S):
        ans = [[]]

        for char in S:
            n = len(ans)
            if char.isalpha():
                for i in range(n):
                    ans.append(ans[i][:])
                    ans[i].append(char.lower())
                    ans[n+i].append(char.upper())
            else:
                for i in range(n):
                    ans[i].append(char)

        return map("".join, ans)

s = Solution()
S = "a1b2c3"
print(list(s.letterCasePermutation(S)))

题目来源:
784. 字母大小写全排列

发布了378 篇原创文章 · 获赞 43 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_43283397/article/details/105019388