题目地址:https://leetcode.com/problems/letter-case-permutation/description/
大意:返回一个列表,列表中列举所有给定字符串中字母所有大小写的情况
思路1:普通的循环添加
class Solution:
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
rlist = [S]
for i,item in enumerate(S):
if not item.isalpha():
continue
l_new = []
for strings in rlist:
swap_str = (strings[:i] + strings[i].swapcase() + strings[i + 1:])
print(swap_str)
l_new.append(swap_str)
rlist.extend(l_new)
return rlist
思路2:DFS算法(参考花花酱的解题思路)
DFS流程图
我们发现,这个二叉树的深度就是字符串的长度。
class Solution:
def letterCasePermutation(self, S):
ans = []
def dfs(S, i, n):
if i == n:
ans.append(''.join(S))
return
dfs(S, i + 1, n)
if not S[i].isalpha(): return
S[i] = S[i].swapcase()
dfs(S, i + 1, n)
S[i] = S[i].swapcase()
dfs(list(S), 0, len(S))
return ans
网友评论