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

c++server side programmingprogramming

假设我们有一个包含字母和数字的字符串。我们需要通过取字符串中字母的大小写形式,生成该字符串的所有可能组合。因此,如果一个字符串只包含数字,则只返回数字。假设该字符串为"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, ]

相关文章