Description
Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string. Return a list of all possible strings we could create.
Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Input: S = "3z4"
Output: ["3z4", "3Z4"]
Input: S = "12345"
Output: ["12345"]
Note:
- S will be a string with length between 1 and 12.
- S will consist only of letters or digits.
分析
题目的意思是:给你一个字符串S,返回这个字符串的所有变换,其中每个字符可以是大写,小写。
- 深度优先搜索问题。
- ‘A’ = 65, ‘B’ = 66, 和 ‘a’ = 97, ‘b’ = 98, 小写字母的ASCII码比大写字母多32,刚好是(1 << 5)即32,那么我们只要变换第五位上的1,就可以实现大小写的交替了。
代码
class Solution {
public:
vector<string> letterCasePermutation(string S) {
vector<string> res;
solve(res,S,0);
return res;
}
void solve(vector<string>& res,string& S,int start){
if(start==S.size()){
res.push_back(S);
return;
}
solve(res,S,start+1);
if(S[start]>'9'){
S[start]^=32;
solve(res,S,start+1);
}
}
};