leetcode_784 字母大小写全排列

119 阅读1分钟

要求

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

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

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

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

提示:

  • S 的长度不超过12。
  • S 仅由数字和字母组成。

核心代码

class Solution:
    def letterCasePermutation(self, s: str) -> List[str]:
        res = [""]
        for c in s:
            next_res = []
            for tmp in res:
                next_res.append(tmp + c)
                if not c.isdigit():
                    c = c.upper() if c.islower() else c.lower()
                    next_res.append(tmp + c)
            res = next_res
        return res

image.png

解题思路:我们使用遍历的方式,首先先对s字符串进行遍历,然后我们将每个加入到输出表中的数据,进行循环最终得到大小写的两个字符加入输出列表中,直到循环结束,我们得到的就是输出数据。