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

更新於: 2020 年 4 月 28 日

228 次瀏覽

開啟你的 事業

完成課程以獲得認證

開始
廣告
© . All rights reserved.