字母大小写全排列

题目描述:
给定一个字符串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);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值