784. Letter Case Permutation
784. Letter Case Permutation
题目
题目即给出一个字符串,然后对数字不做处理,对字母进行排序组合,然后输出排序组合得到的列表。
纯字母大小写排序组合思路参考:
def strSort(words):
tempword = words
for i in range(2**len(words)):
int_bin = str(bin(i)).replace(“0b”,"")
for i in range(len(words)-len(int_bin)):
int_bin = “”.join((“0”,int_bin))
for index, i in enumerate(int_bin):
if i==‘1’:
wordslst = list(words)
wordslst[index] = wordslst[index].upper()
words = “”.join(wordslst)
yield words
words = tempword
for word in strSort(“def”):
想了挺久感觉题目比较难,仅仅考虑到了大小写排列思路怎么写。写出来结果会过于复杂。
于是查询了讨论区:
优秀代码(极其巧妙)
从前往后,没有使用递归,使用了for,效率略低
import itertools
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
res = ['']
for ch in S:
if ch.isalpha():
res = [i+j for i in res for j in [ch.upper(), ch.lower()]]
else:
res = [i+ch for i in res]
return res
从后往前,使用了递归效率更高
class Solution(object):
def letterCasePermutation(self, S):
if len(S) == 0:
return [""]
temp_result = self.letterCasePermutation(S[1:])
c = S[0]
if c.isalpha():
result = [ u+r for u in [c.upper(), c.lower()] for r in temp_result]
else:
result = [ c+r for r in temp_result ]
return result
同样是从后往前,思路没有之前的精巧
class Solution(object):
def letterCasePermutation(self, S):
return self.permute(S)
def permute(self, str):
lenOfStr = len(str)
if lenOfStr == 0:
return [""]
lastElem = str[lenOfStr-1]
str = str[:lenOfStr-1]
tempAns = self.permute(str)
ans = []
for permutation in tempAns:
if lastElem.isalpha():
ans.append(permutation + lastElem.lower())
ans.append(permutation + lastElem.upper())
else:
ans.append(permutation + lastElem)
return ans