C++ 中的字母大小写排列
假设我们有一个包含字母和数字的字符串。我们必须通过获取字符串中存在的字母的大写和 p 版本来生成该字符串的所有可能组合。因此,如果一个字符串只包含数字,则只会返回该数字。假设字符串形如“1ab2”,那么字符串将为 [“1ab2”,“1Ab2”,“1aB2”,“1AB2”]。
为了解决这个问题,我们将使用递归方法。它获取索引参数以此索引作为工作的起点。它还获取到目前为止已创建结果的临时字符串。当索引与字符串长度相同时,则返回临时字符串。对于给定的索引,如果该索引是小写字母,则将其变为大写字母,反之亦然,然后递归执行任务。
示例
让我们看下面的实现以获得更好的理解 −
#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<string> v){
cout << "[";
for(int i = 0; i<v.size(); i++){
cout << v[i] << ", ";
}
cout << "]"<<endl;
}
class Solution {
public:
vector <string> res;
void solve(string s, int idx = 0, string temp = ""){
if(idx == s.size()){
res.push_back(temp);
return;
}
solve(s, idx + 1, temp + s[idx]);
int diff = 'a' - 'A';
if(s[idx] >= 'a' && s[idx] <= 'z'){
char x = (s[idx] - diff);
solve(s, idx + 1, temp + x);
}
else if (s[idx] >= 'A' && s[idx] <= 'Z'){
char x = (s[idx] + diff);
solve(s, idx + 1, temp + x);
}
}
vector<string> letterCasePermutation(string S) {
res.clear();
solve(S);
return res;
}
};
main(){
Solution ob;
print_vector(ob.letterCasePermutation("1ab2"));
print_vector(ob.letterCasePermutation("9876"));
}输入
"1ab2" "9876"
输出
[1ab2, 1aB2, 1Ab2, 1AB2, ] [9876, ]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP