题目:
给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
示例:
输入: S = "a1b2"
输出: ["a1b2", "a1B2", "A1b2", "A1B2"]
输入: S = "3z4"
输出: ["3z4", "3Z4"]
输入: S = "12345"
输出: ["12345"]
注意:
S 的长度不超过12。
S 仅由数字和字母组成。
链接:https://leetcode-cn.com/problems/letter-case-permutation
思路:
1、采用递归的思想,结果等价于首字母拼接上 去除首字母的结果的值
Python代码:
class Solution(object):
def letterCasePermutation(self, S):
"""
:type S: str
:rtype: List[str]
"""
if not S:
return [S]
ret = self.letterCasePermutation(S[1:])
if S[0].encode('utf-8').isdigit():
return [S[0]+item for item in ret]
else:
return [S[0].lower()+item for item in ret] + [S[0].upper()+item for item in ret]
C++代码:
class Solution {
public:
vector<string> letterCasePermutation(string S) {
if (S==""){
return {S};
}
int size = S.size();
vector<string> ret = letterCasePermutation(S.substr(1,size));
if (isdigit(S[0])!=0){
for(string &item : ret){
item = S[0]+item;
}
return ret;
}else{
vector<string> ret_cp_lower(ret);
vector<string> ret_cp_upper(ret);
for (string &item:ret_cp_lower){
char first_item = tolower(S[0]);
item = first_item+item;
}
for (string &item:ret_cp_upper){
char first_item = toupper(S[0]);
item = first_item+item;
}
ret_cp_lower.insert(ret_cp_lower.end(),ret_cp_upper.begin(),ret_cp_upper.end());
return ret_cp_lower;
}
}
};
C++代码:
class Solution {
public:
vector<string> letterCasePermutation(string S) {
if (S==""){
return {S};
}
int size = S.size();
vector<string> ret = letterCasePermutation(S.substr(1,size));
if (isdigit(S[0])!=0){
for(string &item : ret){
item = S[0]+item;
}
return ret;
}else{
vector<string> ret_new;
for (string item:ret){
char first_item = tolower(S[0]);
item = first_item+item;
ret_new.push_back(item);
}
for (string item:ret){
char first_item = toupper(S[0]);
item = first_item+item;
ret_new.push_back(item);
}
return ret_new;
}
}
};