Letter Case Permutation in C++


Suppose we have a string with letters and numbers. We have to generate all possible combinations of that string by taking uppercase and lowercase versions of letters that are present in the string. So if one string has only numbers, only that will be returned. Suppose the string is like “1ab2”, then the strings will be [“1ab2”, “1Ab2”, “1aB2”, “1AB2”]

To solve this problem, we will use recursive approach. It takes the index parameter to start work from that index. It also takes a temp string up to which the result is created. When the index is same as the string length, then return the temp string. For the given index, if that is lowercase letter, make it to uppercase and vice-versa, then recursively do the task.

Example

Let us see the following implementation to get better understanding −

 Live Demo

#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"));
}

Input

"1ab2"
"9876"

Output

[1ab2, 1aB2, 1Ab2, 1AB2, ]
[9876, ]

Updated on: 28-Apr-2020

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements