题目描述:
给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
方法一:
如果下一个字符 x是字母,将当前已遍历过的字符串全排列复制两份,在第一份的每个字符串末尾添加 lowercase(x),在第二份的每个字符串末尾添加 uppercase(x)。
如果下一个字符 x 是数字,将 x直接添加到每个字符串的末尾。
class Solution {
public List<String> letterCasePermutation(String S) {
List<StringBuffer> res=new ArrayList<>();
res.add(new StringBuffer());
for(char x:S.toCharArray()){
int n=res.size();
if(Character.isLetter(x)){
for(int i=0;i<n;i++){
res.add(new StringBuffer(res.get(i)));
res.get(i).append(Character.toLowerCase(x));
res.get(i+n).append(Character.toUpperCase(x));
}
}else{
for(int i=0;i<n;i++){
res.get(i).append(x);
}
}
}
List<String> r=new ArrayList<>();
for(StringBuffer x:res){
r.add(x.toString());
}
return r;
}
}
方法二:回溯法
class Solution {
List<String> res=new ArrayList<>();
public List<String> letterCasePermutation(String S) {
dfs(S.toCharArray(),0,S.length());
return res;
}
public void dfs(char[] s,int index,int len){
if(index==len){
res.add(new String(s));
return;
}
dfs(s,index+1,len);
if(s[index]>='A'){
s[index]=s[index]<'a'?(char)(s[index]+32):(char)(s[index]-32);
dfs(s,index+1,len);
}
}
}