力扣网
题目描述:给定一个字符串S
,通过将字符串S
中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
class Solution {
public:
vector<string> my_letter;
vector<string> letterCasePermutation(string S) {
return letter(S,0);
}
vector<string> letter(string& S,int index)
{
if (index == S.size())
{
my_letter.push_back(S);
return my_letter;
}
letter(S,index+1);
if (isalpha(S[index]))
{
S[index]^=(1<<5);
return letter(S,index+1);
}
return my_letter;
}
};
回溯法。递推返回时,函数参数是否为引用,会影响最终组合顺序
参考资料
https://www.cnblogs.com/grandyang/p/9065702.html
我们知道 'A' = 65, 'B' = 66, 和 'a' = 97, 'b' = 98, 小写字母的ASCII码比大写字母多32,刚好是(1 << 5),那么我们只要flip第五位上的1,就可以实现大小写的交替了
a= 01100001;
32=00100000;
A= 01000001