题目
给定一个字符串S
,通过将字符串S
中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例: 输入: S = "a1b2" 输出: ["a1b2", "a1B2", "A1b2", "A1B2"] 输入: S = "3z4" 输出: ["3z4", "3Z4"] 输入: S = "12345" 输出: ["12345"]
注意:
S
的长度不超过12
。S
仅由数字和字母组成。
分析
回溯算法,遍历字符串,判断是数字,大写字母,小写字母,做相应的处理。
数字的时候直接添加到字符串temp后面然后递归,如果是字母,需要把字母本身添加到temp字符串后面,递归完之后还要把字母本身从temp后面去掉,然后将其变身(大写变小写,小写变大写)放到temp字符串后面再递归调用。
代码
class Solution {
public List<String> letterCasePermutation(String S) {
List<String> list = new ArrayList<>();
String temp = "";
letter(list,S,temp,0);
return list;
}
public static void letter(List<String> list,String S, String temp , int index){
if (S.length() == temp.length()) list.add(temp);
if (index == S.length()) return;
temp+=S.charAt(index);
letter(list,S,temp,index+1);
temp = temp.substring(0,temp.length()-1);
if (S.charAt(index) >= 'a' && S.charAt(index) <= 'z'){//小写字母a-z
temp += (char)(S.charAt(index) + 'A' - 'a');
letter(list,S,temp,index+1);
}else if(S.charAt(index) >= 'A' && S.charAt(index) <= 'Z'){//大写字母A-Z
temp += (char)(S.charAt(index) + 'a' - 'A');
letter(list,S,temp,index+1);
}
}
}