给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例:
输入: S = “a1b2”
输出: [“a1b2”, “a1B2”, “A1b2”, “A1B2”]
输入: S = “3z4”
输出: [“3z4”, “3Z4”]
输入: S = “12345”
输出: [“12345”]
class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> ans;
dfs(S,ans,0);
return ans;
}
void dfs(string S,vector<string>& ans,int index){
if(index>=S.size()){
ans.push_back(S);
return;
}
if(isalpha(S[index])){
dfs(S,ans,index+1);
if(isupper(S[index])){
S[index]=tolower(S[index]);
dfs(S,ans,index+1);
}
else{
S[index]=toupper(S[index]);
dfs(S,ans,index+1);
}
}else dfs(S,ans,index+1);
}
};
同样的思路,这次往tep上面添加字符,可能速度上快一点。上面的是在复制的字符串上操作。
递归思路:
1.结束条件:tep长度达到要求
2.主体:
- 如果当前是数字,直接加到tep上
- 字母的话,加到tep上,然后转换大小写再次加到tep上
- 看下一次字符是啥
class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> ans;
string tep;
dfs(S,ans,0,tep);
return ans;
}
void dfs(string S,vector<string>& ans,int index,string tep){
if(index>=S.size()){
ans.push_back(tep);
return;
}
if(isalpha(S[index])){
char a=S[index];
tep.push_back(a);
dfs(S,ans,index+1,tep);
if(isupper(a)) a=tolower(a);
else a=toupper(a);
tep.pop_back();
tep.push_back(a);
dfs(S,ans,index+1,tep);
}else {
tep.push_back(S[index]);
dfs(S,ans,index+1,tep);
}
}
};
此图放这,目的: