IT虾米网

字母大小写全排列

developer 2022年05月03日 程序员 257 0

给定一个字符串 s ,通过将字符串 s 中的每个字母转变大小写,我们可以获得一个新的字符串。

返回 所有可能得到的字符串集合 。以 任意顺序 返回输出。

示例 1:

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

示例 2:

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

示例代码1:【递归】

class Solution(): 
    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[i + n].append(char.upper()) 
            else: 
                for i in range(n): 
                    ans[i].append(char) 
        return list(map("".join, ans)) 
 
s1 = "a1b2" 
s2 = "1b2" 
obj = Solution() 
ret = obj.letterCasePermutation(s2) 
print(ret) 

思路解析:【递归】

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

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

  • 如果下一个字符 c 是字母,将当前已遍历过的字符串全排列复制两份,在第一份的每个字符串末尾添加 lowercase(c),在第二份的每个字符串末尾添加 uppercase(c)。
  • 如果下一个字符 c 是数字,将 c 直接添加到每个字符串的末尾。

复杂度分析:

 示例代码2: 【回溯】

class Solution(): 
    def letterCasePermutation(self, s): 
        # 就两种选择:转换和不转换 
        def dfs(path, index): 
            if index == len(s): 
                ans.append(path) 
                return 
            if s[index].isdigit():  # 是数字,直接加进去 
                dfs(path + s[index], index + 1) 
            else:  # 是字母 
                # dfs(path + s[index], index + 1) 
                # 转 
                if s[index].islower():  # 小写转大写 
                    dfs(path + s[index].upper(), index + 1) 
                else:  # 大写转小写 
                    dfs(path + s[index].lower(), index + 1) 
                # 不转 
                dfs(path + s[index], index + 1) 
 
        ans = [] 
        dfs("", 0) 
        return ans 
 
 
s1 = "a1b2" 
s2 = "1b2" 
obj = Solution() 
ret = obj.letterCasePermutation(s1) 
print(ret) 

思路解析:

三种选择:
1.如果是大写则转换为小写
2.如果是小写则转换为大写
3.不进行转换

示例代码3:

class Solution(): 
    def letterCasePermutation(self, s): 
        ans = [''] 
        for i in s.lower(): 
            ans = [j + i for j in ans] + ([j + i.upper() for j in ans] if i.isalpha() else []) 
        return ans 
 
 
s1 = "a1b2c3d" 
s2 = "1b2" 
obj = Solution() 
ret = obj.letterCasePermutation(s1) 
print(ret) 

思路解析:

        首先全小写化,然后每个字符依次判断,数字则加入原字符,字母则分别加入原字符及其大写。


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!

整数转罗马数字