LeetCode 题解工作台
字母大小写全排列
给定一个字符串 s ,通过将字符串 s 中的每个字母转变大小写,我们可以获得一个新的字符串。 返回 所有可能得到的字符串集合 。以 任意顺序 返回输出。 示例 1: 输入: s = "a1b2" 输出: ["a1b2", "a1B2", "A1b2", "A1B2"] 示例 2: 输入: s = "…
3
题型
6
代码语言
3
相关题
当前训练重点
中等 · 回溯·pruning
答案摘要
由于 中的每个字母都可以转换为大写或小写,因此可以使用 DFS 深度优先搜索的方法,枚举所有可能的情况。 具体地,从左到右遍历字符串 ,对于遍历到的每个字母,可以选择将其转变为大写或小写,然后继续遍历后面的字母。当遍历到字符串的末尾时,得到一个转换方案,将该方案加入答案即可。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 回溯·pruning 题型思路
题目描述
给定一个字符串 s ,通过将字符串 s 中的每个字母转变大小写,我们可以获得一个新的字符串。
返回 所有可能得到的字符串集合 。以 任意顺序 返回输出。
示例 1:
输入:s = "a1b2" 输出:["a1b2", "a1B2", "A1b2", "A1B2"]
示例 2:
输入: s = "3z4" 输出: ["3z4","3Z4"]
提示:
1 <= s.length <= 12s由小写英文字母、大写英文字母和数字组成
解题思路
方法一:DFS
由于 中的每个字母都可以转换为大写或小写,因此可以使用 DFS 深度优先搜索的方法,枚举所有可能的情况。
具体地,从左到右遍历字符串 ,对于遍历到的每个字母,可以选择将其转变为大写或小写,然后继续遍历后面的字母。当遍历到字符串的末尾时,得到一个转换方案,将该方案加入答案即可。
转变大小写的方法可以使用位运算实现。对于一个字母,小写形式与大写形式的 ASCII 码之差为 ,因此,我们可以通过将该字母的 ASCII 码与 进行异或运算来实现大小写转换。
时间复杂度 ,其中 是字符串 的长度。对于每个字母,我们可以选择将其转换为大写或小写,因此一共有 种转换方案。对于每种转换方案,我们需要 的时间生成一个新的字符串。
class Solution:
def letterCasePermutation(self, s: str) -> List[str]:
def dfs(i: int) -> None:
if i >= len(t):
ans.append("".join(t))
return
dfs(i + 1)
if t[i].isalpha():
t[i] = chr(ord(t[i]) ^ 32)
dfs(i + 1)
t = list(s)
ans = []
dfs(0)
return ans
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | and space complexity depend on the number of alphabetic characters in the string. The number of possible permutations grows exponentially with each letter that has two case options. Specifically, for a string of length `n`, with `k` alphabetic characters, the time and space complexity are both O(2^k), as each letter has two choices (uppercase or lowercase). |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- question_mark
Candidate demonstrates knowledge of backtracking and its application to case permutations.
- question_mark
Ability to prune the search space and optimize the recursion depth for efficiency.
- question_mark
Candidate can explain the trade-offs between recursive and iterative solutions.
常见陷阱
外企场景- error
Not correctly handling digits or non-alphabetic characters, which should remain unchanged.
- error
Failure to optimize the backtracking approach by pruning unnecessary recursion calls.
- error
Not understanding the exponential time complexity caused by processing alphabetic characters.
进阶变体
外企场景- arrow_right_alt
Allowing more than one non-alphabetic character in the string.
- arrow_right_alt
Exploring iterative methods rather than backtracking for generating permutations.
- arrow_right_alt
Adding constraints on the number of operations or runtime limits to challenge the approach.