784. Letter Case Permutation
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.
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 at most12
.S
will consist only of letters or digits.
My Solutions:
和combinations 类似,加入list的条件是index == s.length(), 即所有char已经加入
如果char是letter,需要lower case和upper case都dfs一遍
方法1:和模板类似
class Solution {
public List<String> letterCasePermutation(String S) {
List<String> list = new ArrayList<>();
dfs(S, new StringBuilder(), list, 0);
return list;
}
public void dfs(String s, StringBuilder sb, List<String> list, int pos) {
if (pos == s.length()) {
list.add(sb.toString());
return;
}
char c = s.charAt(pos);
if (Character.isDigit(c)) {
sb.append(c);
dfs(s, sb, list, pos + 1);
} else {
sb.append(Character.toLowerCase(c));
dfs(s, sb, list, pos + 1);
sb.deleteCharAt(sb.length() - 1);
sb.append(Character.toUpperCase(c));
dfs(s, sb, list, pos + 1);
}
sb.deleteCharAt(sb.length() - 1);
}
}
方法2:把s变成char[] arr
class Solution {
public List<String> letterCasePermutation(String S) {
List<String> list = new ArrayList<>();
dfs(list, S.toCharArray(), 0);
return list;
}
private void dfs(List<String> list, char[] arr, int index) {
if (index == arr.length) {
list.add(new String(arr));
return;
}
if (Character.isLetter(arr[index])) {
arr[index] = Character.toLowerCase(arr[index]);
dfs(list, arr, index + 1);
arr[index] = Character.toUpperCase(arr[index]);
}
dfs(list, arr, index + 1);
}
}
Last updated