Description:
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 between 1 and 12.
- S will consist only of letters or digits.
题意:给定一个字符串,对其中的字母进行任意数量的大小写转换,要求返回所有可能的结果;
解法:很容易想到可以利用递归和回溯来解决这个问题;用index记录当前字符串的遍历位置,我们每次从当前位置遍历字符串,找到第一个出现的字母,将其进行大小写的转换得到一个新的字符串temp(temp就是结果种的一种可能),之后可以再对字符串temp利用上面的方法重新找到第一个出现字母的位置又可以得到一个新的字符串,直到index超出了字符串的长度后我们可以执行回溯,返回最近一次修改字母大小写的位置处,不执行修改直接执行上述的操作;
Java
class Solution {
public List<String> letterCasePermutation(String S) {
List<String> result = new ArrayList<>();
result.add(S);
permutation(result, S, 0);
return result;
}
private void permutation(List<String> result, String S, int index) {
if (index >= S.length()) return;
for (int i = index; i < S.length(); i++) {
char ch = S.charAt(i);
String temp = "";
if (!Character.isLetter(ch)) continue;
if (Character.isLowerCase(ch)) {
temp = S.substring(0, i) + Character.toUpperCase(ch) + S.substring(i+1);
} else {
temp = S.substring(0, i) + Character.toLowerCase(ch) + S.substring(i+1);
}
result.add(temp);
permutation(result, temp, i+1);
}
}
}