Daily LeetCode 784. Letter Case Permutatio

https://leetcode.com/problems/letter-case-permutation/

Easy

问题描述:

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.

1
2
3
4
5
6
7
8
9
Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]

Input: S = "3z4"
Output: ["3z4", "3Z4"]

Input: S = "12345"
Output: ["12345"]

Note:

  • S will be a string with length between 1 and 12.
  • S will consist only of letters or digits.

题目分析:

给定一个由字母和数字组成的字符串,我们需要返回一个基于所有字母大小写全排列构成的字符串列表。

这一题对数字不需要任何的处理,只要简单加上即可,主要还是对字母的处理。我们可以利用python中列表操作的特性来解决这条题目。首先,对字符串进行遍历,遇到字母ch时,将ch的大小写分别添加到结果列表中。

代码:

1
2
3
4
5
6
7
8
9
class Solution:
def letterCasePermutation(self, S: str) -> List[str]:
res = ['']
for ch in S:
if ch.isalpha():
res = [res_sub + ch.upper() for res_sub in res] + [res_sub + ch.lower() for res_sub in res]
else:
res = [res_sub + ch for res_sub in res]
return res