leetcode 784. Letter Case Permutation
题目描述
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.
Note:
- S will be a string with length at most 12.
- S will consist only of letters or digits.
Difficulty: easy
784. Letter Case Permutation
中文描述
在给定一个字符串S(只包含大小写字母和数字),需要我们得到在只修改大小写,而不改变顺序的情况下,所有可能字符串的列表
Examples:
Input: S = “a1b2”
Output: [“a1b2”, “a1B2”, “A1b2”, “A1B2”]Input: S = “3z4”
Output: [“3z4”, “3Z4”]Input: S = “12345”
Output: [“12345”]
解答思路
从每个字符串的第n位开始考虑,如果该位是字母,则可以有大写和小写两种情况,这边就有了分支。如果是数字则只存在唯一的分支。之后每个分支的前n位就固定,我们需要从n+1位开始考虑,重复上诉操作直到到达字符串的最后一位。
以a1b2
为例,第1位开始考虑,第1位是a
是字母,则之后有A1b2,a1b2
两种情况。然后分别考虑A1b2,a1b2
各自的分支,以A1b2
这条分支为例,第2位是1,所以还是A1b2
,之后第三位是b
,存在分支A1B2,A1b2
,A1B2,A1b2
之后第3位又是数字,所以A1B2,A1b2
之后的分支只有A1B2,A1b2
。所以把A1B2,A1b2
添加到列表里。同理,对于a1b2
的分支可以添加a1b2,a1B2
,最后答案就是a1b2,a1B2,A1B2,A1b2
代码
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
131ms
"""
# 记录当前所有的分支
cur_s =[S]
# 每次都从上一轮记录的位置的下一位开始计算
for i in range(len(S)):
next_s = []
for s in cur_s:
# 如果是数字,则当前分支直接加入下轮的分支
if s[i].isdigit():
next_s.append(s)
# 如果是字母,则当前分支分为大小写两种加入下轮的分支
else:
next_s.append(s[0:i] + s[i].lower() + s[i + 1:])
next_s.append(s[0:i] + s[i].upper() + s[i + 1:])
cur_s = next_s
return cur_s