1032. Letter Case Permutation
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.
Example
Example 1:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]
Example 2:
Input: S = "3z4"
Output: ["3z4", "3Z4"]
Example 3:
Input: S = "12345"
Output: ["12345"]
Notice
S will be a string with length at most 12.
S will consist only of letters or digits.
Input test data (one parameter per line)How to understand a testcase?
解法1:用DFS。类似subsets的第一类组合类DFS搜索模板。
每个字母都有选本身和变大/小写两种可能,类似subsets的选或不选。
注意,“字母选本身”和"遇到非字母"这两种情况处理方法一样,所以代码都是helper(S, index + 1, result);。
代码如下:
class Solution {
public:
/**
* @param S: a string
* @return: return a list of strings
*/
vector<string> letterCasePermutation(string &S) {
int n = S.size();
if (n == 0) return {""};
vector<string> result;
helper(S, 0, result);
return result;
}
private:
void helper(string & S, int index, vector<string> & result) {
if (index == S.size()) {
result.push_back(S);
return;
}
helper(S, index + 1, result);
if (isalpha(S[index])) {
if (S[index] >= 'A' && S[index] <= 'Z') {
S[index] += 'a' - 'A';
}
else {
S[index] -= 'a' - 'A';
}
helper(S, index + 1, result);
}
}
};
解法2:DFS第二类模板(适合通用DFS问题)
class Solution {
public:
/**
* @param S: a string
* @return: return a list of strings
*/
vector<string> letterCasePermutation(string &S) {
int n = S.size();
if (n == 0) return {""};
vector<string> result;
string sol = S;
helper(S, 0, result, sol);
return result;
}
private:
void helper(string S, int index, vector<string> & result, string & sol) {
result.push_back(sol);
for (int i = index; i < S.size(); ++i) {
if (isalpha(S[i])) {
if (S[i] >= 'A' && S[i] <= 'Z') {
sol[i] = S[i] + 'a' - 'A';
}
else {
sol[i] = S[i] - ('a' - 'A');
}
helper(S, i + 1, result, sol);
if (S[i] >= 'A' && S[i] <= 'Z') {
sol[i] = S[i];
}
else {
sol[i] = S[i];
}
}
}
}
};
也可以不用那个sol,还是在S上操作。
class Solution {
public:
/**
* @param S: a string
* @return: return a list of strings
*/
vector<string> letterCasePermutation(string &S) {
int n = S.size();
if (n == 0) return {""};
vector<string> result;
string sol = S;
helper(S, 0, result);
return result;
}
private:
void helper(string & S, int index, vector<string> & result) {
result.push_back(S);
for (int i = index; i < S.size(); ++i) {
if (isalpha(S[i])) {
if (S[i] >= 'A' && S[i] <= 'Z') {
S[i] += 'a' - 'A';
}
else {
S[i] -= 'a' - 'A';
}
helper(S, i + 1, result);
if (S[i] >= 'A' && S[i] <= 'Z') {
S[i] += 'a' - 'A';
}
else {
S[i] -= 'a' - 'A';
}
}
}
}
};
本文介绍了一种通过深度优先搜索(DFS)实现的算法,用于生成给定字符串中所有可能的大小写排列组合。该算法适用于长度不超过12的字符串,能够处理字母和数字,并返回所有可能的字符串变化形式。
482

被折叠的 条评论
为什么被折叠?



