LeetCode 784. Letter Case Permutation

本文介绍了一种通过枚举字符串中字母的大小写状态来生成所有可能字符串组合的算法。利用二进制数表示每种状态,实现了字符串a1b2等类似输入的所有变换。文章详细解释了算法原理,并提供了C++实现代码。

原题链接

Given a string S, we can transform every letter individually to be lowercase or uppercase to create another string.  Return a list of all possible strings we could create.

Examples:
Input: S = "a1b2"
Output: ["a1b2", "a1B2", "A1b2", "A1B2"]

Input: S = "3z4"
Output: ["3z4", "3Z4"]

Input: S = "12345"
Output: ["12345"]
Note:

S will be a string with length at most 12.
S will consist only of letters or digits.

分析:每个字母可大写可小写,用0,1代表该字母的大小写的状态,1为大写。若字符串为a1b2,包含两个字母,则两个字母所有的状态组合为{00,01,10,11},将枚举状态看作二进制数,则化为十进制为{0,1,2,3},这样问题就能很好地被解决了。

#include<iostream>
#include<vector>
#include<string>
#include<bitset>
#include<math.h>
using namespace std;

vector<string> letterCasePermutation(string& s)
{
   vector<string> ans;
   vector<int> letterPos;
   
   int mark = 1,size = s.size();
   if(size == 0 ) return ans;

   for(int i = 0; i < size; i++)
   {
       if(isalpha(s[i]))
       {
           s[i] = tolower(s[i]);
           mark *= 2;
           letterPos.push_back(i);
       }
   }

   for(int i = 0; i < mark; i++)
   {
       int t = i;
       string ts = s;
       for(int j = 0;j < letterPos.size(); j++)
       {
           //cout << t << " " << j << " " << (t >> j) % 2 << endl;
           if((t >> j) % 2 == 1) 
           {
               ts[letterPos[letterPos.size() - 1 - j]] = toupper(s[letterPos[letterPos.size() - 1 - j]]);
           }
           //ts[letterPos[j]] = (t >> j) % 2 == 1 ? toupper(s[letterPos[j]]) : s[letterPos[j]];
       }
       cout << ts << endl;
       ans.push_back(ts);

   }

   return ans;
}
int main()
{
   string s;
   s = "a1b2";
   vector<string> ans = letterCasePermutation(s);
   //for(int i = 0;i < ans.size(); i++)  cout << ans[i] << endl;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值