784. Letter Case Permutation

答案
Given a string s, you can transform every letter individually to be lowercase or uppercase to create another string.

Return a list of all possible strings we could create. Return the output in any order.

当前字符如果为数字,则直接添加并递归。(将字符隐式转换为整数判断是否为数字,可提升速度。)
当前字符如果为字母,则大小写分别添加到递归。(类似于回溯。)
当字符串长度与搜寻字符串相等时,添加到列表。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
class Solution {
List<String> ans;
String _s;
public List<String> letterCasePermutation(String s) {
ans = new ArrayList();
_s = s;

backTrack(new StringBuilder(),0);
return ans;

}

private void backTrack(StringBuilder sb, int i){
if(i == _s.length()){
ans.add(sb.toString());
return;
}
char curr = _s.charAt(i);
if ( isNums(curr) ){
sb.append(curr);
backTrack(sb, i+1);
}
else{
StringBuilder sb2 = new StringBuilder(sb);
sb.append(Character.toLowerCase(curr));
backTrack(sb, i+1);
sb2.append(Character.toUpperCase(curr));
backTrack(sb2, i+1);
}
}

private boolean isNums(char c){
if ( (int)c >= (int)'0' && (int)c <= (int)'9' ){
return true;
}
return false;
}
}
Author

Xander

Posted on

2022-04-13

Updated on

2022-04-23

Licensed under

Comments