algorithm notes: leetcode#784 letter case permutation

Problem


Solution


Analysis

Python implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class :
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
ans = ['']
for c in S:
if c.isalpha():
ans = [t+c.lower() for t in ans] + [t+c.upper() for t in ans]
else:
ans = [t+c for t in ans]
return ans

Java implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
class {
public List<String> letterCasePermutation(String S) {
List<String> ans = new ArrayList<>();
ans.add("");
for(char c : S.toCharArray()){
if(Character.isLetter(c)){
List<String> newAns = new ArrayList<>();
for(String t : ans){
newAns.add(t+Character.toString(Character.toLowerCase(c)));
newAns.add(t+Character.toString(Character.toUpperCase(c)));
}
ans = newAns;
}else{
for(int i = 0; i < ans.size(); i++){
ans.set(i, ans.get(i) + Character.toString(c));
}
}
}
return ans;
}
}

Time complexity

O(2^N * N).

Space complexity

O(2^N * N).


784. Letter Case Permutation
(中文版) 算法笔记: 力扣#784 字母大小写全排列