本文的目的是收集一些典型的题目,记录其题型与解法,理解其思想,即做到一通百通!
欢迎大家提出宝贵意见!
题目
题目简介
给定一个字符串 s ,通过将字符串 s 中的每个字母转变大小写,我们可以获得一个新的字符串。
返回 所有可能得到的字符串集合 。以 任意顺序 返回输出。
示例 1:
输入:s = "a1b2"
输出:["a1b2", "a1B2", "A1b2", "A1B2"]
示例 2:
输入: s = "3z4"
输出: ["3z4","3Z4"]
提示:
1 <= s.length <= 12
s
由小写英文字母、大写英文字母和数字组成
题解
暴力解法,直接将字母分两种情况添加,数字直接添加。
直接看代码:
class Solution {
public:
vector<string> res;
// 思路:大小写字符取两种情况即可;数字直接添加
vector<string> letterCasePermutation(string s) {
int n=s.size();
backtrack(s,"",0,n);
return res;
}
void backtrack(string s,string path,int i,int n){
if(i==n){res.push_back(path);return;}
// 数字直接添加进答案
if(s[i]>='0'&&s[i]<='9') backtrack(s,path+s[i],i+1,n);
else{
// 字母就原字母和转换之后的字母两种情况,然后进行下一层的枚举
backtrack(s,path + s[i],i+1,n);
backtrack(s,path + char(s[i]^32),i+1,n);
}
}
};
优化后的深度优先搜索 Java 代码:
class Solution {
List<String> res = new ArrayList<>();
public List<String> letterCasePermutation(String S) {
char[] chs = S.toCharArray();
int n = chs.length;
dfs(chs, n, 0);
return res;
}
private void dfs(char[] chs, int n, int begin) {
res.add(new String(chs));
for(int i = begin; i < n; i++){
if(!Character.isDigit(chs[i])){
char tmp = chs[i];
chs[i] = (char)(chs[i] - 'a' >= 0 ? chs[i] - 32 : chs[i] + 32);
dfs(chs, n, i + 1);
chs[i] = tmp;
}
}
}
}
回溯 Java 代码:
class Solution {
List<String> ans = new ArrayList<String>();
public List<String> letterCasePermutation(String s) {
StringBuilder path = new StringBuilder(s);
dfs(s, 0, path);
return ans;
}
public void dfs(String s, int pos, StringBuilder path) {
if (pos == s.length()) {
ans.add(path.toString());
return;
}
// 是数字,就直接放到答案里,进行下一个字符的递归
if (Character.isDigit(s.charAt(pos))) {
path.setCharAt(pos, s.charAt(pos));
dfs(s, pos + 1, path);
// 是小写字符,分两种情况,直接添加进答案以及变成大写后添加进答案
} else if (Character.isLowerCase(s.charAt(pos))) {
path.setCharAt(pos, s.charAt(pos));
dfs(s, pos + 1, path);
path.setCharAt(pos, Character.toUpperCase(s.charAt(pos)));
dfs(s, pos + 1, path);
} else {
// 大写字符与小写同理
path.setCharAt(pos, s.charAt(pos));
dfs(s, pos + 1, path);
path.setCharAt(pos, Character.toLowerCase(s.charAt(pos)));
dfs(s, pos + 1, path);
}
}
}