C ++中的字母大小写排列

假设我们有一个包含字母和数字的字符串。我们必须通过获取字符串中存在的字母的大写和小写版本来生成该字符串的所有可能组合。因此,如果一个字符串只有数字,则只会返回数字。假设字符串类似于“ 1ab2”,则字符串将为[“ 1ab2”,“ 1Ab2”,“ 1aB2”,“ 1AB2”]

为了解决这个问题,我们将使用递归方法。它需要index参数才能从该索引开始工作。它还需要一个临时字符串,直到创建结果为止。当索引与字符串长度相同时,则返回临时字符串。对于给定的索引,如果是小写字母,则使其变为大写字母,反之亦然,然后递归执行该任务。

示例

让我们看下面的实现以更好地理解-

#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, ]