其他分享
首页 > 其他分享> > 784 字母大小写全排列

784 字母大小写全排列

作者:互联网

题目描述:
给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。

示例:
输入:S = “a1b2”
输出:[“a1b2”, “a1B2”, “A1b2”, “A1B2”]

输入:S = “3z4”
输出:[“3z4”, “3Z4”]

输入:S = “12345”
输出:[“12345”]

提示:
S 的长度不超过12。
S 仅由数字和字母组成。

方法1:
主要思路:解题链接汇总
(1)确定每个字母的大小写,来获得不同的字符串,和二进制的01表示对应,故考虑使用从0到最大值之间的各个数字的01排布,来确定对应位置的大小写字母;
(2)字母的个数是size,则对应的最大数为pow( 2,size )-1;

class Solution {
public:
    vector<string> letterCasePermutation(string S) {
        vector<pair<int,int>> mp;//获得字母的分布,first是字母的索引位置,second是对应的0到25的整数;
        for(int i=0;i<S.size();++i){
            if(S[i]>='a'&&S[i]<='z'){
                mp.push_back({i,S[i]-'a'});
            }
            else if(S[i]>='A'&&S[i]<='Z'){
                mp.push_back({i,S[i]-'A'});
            }
        }
        int end=pow(2,mp.size());//终止数字
        int index=0;//起始数字
        vector<string>res;//结果
        while(index<end){
            int cur_index=index;//当前数字
            ++index;
            for(pair<int,int>&it:mp){
                if(cur_index&1){//根据0,1分布确定各个字母的大小写
                    S[it.first]=it.second+'A';
                }
                else{
                    S[it.first]=it.second+'a';
                }
                cur_index>>=1;
            }
            res.push_back(S);//获得当前字符串
        }
        return res;
    }
};

标签:784,index,int,字母,大小写,mp,字符串
来源: https://blog.csdn.net/weixin_44171872/article/details/113590997