字符串组合

以一个简单的字符串题开始我的博客。

题目:输入一个字符串,给出这个字符串中字符的组合。如:输入abc,它的组合有a、b、c、ab、ac、bc、abc。


分析:对于每个字母都有两种选择,选他或者不选他,我们可以用一个二进制位表示选择情况,1表示选择,0表示不选择,如ab = 110, c = 001, abc = 111。而且abc我们可以通过ab和c这两个字符串相加得到。所以我们可以通过自底向上的方法,缓存中间结果,省去不必要的重复计算。


代码:

#include <iostream>
#include <string>
#include <vector>
#include <math.h>

using namespace std;

string strInput("abcd");



void main()
{
	int TableSize = 1;
	for (int i = 0; i < strInput.length(); ++i)
	{
		TableSize *= 2;
	}
	//初始化字符串表,长度2^length
	vector<string> stringTable(TableSize);
	stringTable[0] = "";
	//currentBit用于标识现在处理的哪一位,currentNum用于标识应减去的最高位值,用于对子字符串的索引
	int currentBit = 0;
	int currentNum = 1;
	int inputLength = strInput.length();
	for (int i = 1; i < TableSize; ++i)
	{
		if (i == currentNum * 2)
		{
			++currentBit;
			currentNum *= 2;
		}
		//索引子字符串
		int substrIndex = i - currentNum;
		stringTable[i] = strInput.substr(inputLength - currentBit - 1, 1) + stringTable[substrIndex];
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值