数据结构基础(11)------------输出字符串的所有组合( Permutation)--腾讯笔试附加题

数据结构基础(11)------------输出字符串的所有组合( Permutation)
腾讯笔试附加题
1.题目介绍:给出一个字符串的所有排列,例如“abc”输出,“a,b,c,ab,ac,bc,abc”;
2.首先应当考虑测试用例:
                                          1.功能测试:“adcd”,"aabd","abbd","abdd";
                                          2.特殊值输入测试:输入空指针,输入空串;
3.代码实现:
//此函数用于将所有位于current_items的添加到另一个容器内
void add_vector_to_vector(vector<char *> &items,const vector<char *> &current_items)
{
	for (const auto &p:current_items)
	{
		items.push_back(p);
	}
}
//将一个字符串添加到当前容器内
void add_str_to_vetor(char *pstr,vector<char *> ¤t_items)
{        //判断是否已经存在此字符串
	for (auto &x:current_items)
	{
		char *m=x;
		char *n=pstr;
		while (*m==*n)
		{
			if (*m=='\0')
			{
				return ;//已存在字符串,直接返回,不再添加。完成去重复的功能。
			}
			m++;
			n++;
		}
	}

	int i=0;
	while (pstr[i++]!='\0') //计算字符串的个数
	{
	}
	char *p=new char[i];
	for (int j=0;j<=i-1;j++)//复制字符串并添加至容器
	{
		p[j]=pstr[j];
	}
	current_items.push_back(p);
}
//核心函数,对于给定的字符串,产生出当前字符的全排列。
void permutation(char *str,char *pbegin,vector<char *> ¤t_items)
{
    if (nullptr==str || nullptr==pbegin)
    {
		return ;
    }
	if ('\0'==*pbegin)
	{
		add_str_to_vetor(str,current_items);
		return ;
	}
	
	for (char *pch=pbegin;*pch!='\0';pch++)
	{
		char temp=*pbegin;
		*pbegin=*pch;
		*pch=temp;
		permutation(str,pbegin+1,current_items);
		temp=*pbegin;
		*pbegin=*pch;
		*pch=temp;	
	}
}


void print_permutation(char *str,int length)
{
		
	if (nullptr==str || length<=0)
	{
		return ;
	}
	vector<char *> items;
	for (int i=1;i<=length;++i)
	{
		vector<char *> current_items;
		for (int k=0;k<length;k++)
		{   
			char *p=new char[i+1];
			p[i]='\0';
			for (int j=0;j<i;++j)
			{
				p[j]=str[(j+k)%length];
			}	
			permutation(p,p,current_items);
			
		}
		add_vector_to_vector(items,current_items);
	}
	for (auto &x:items)
	{
		cout<<x<<endl;
	}
}





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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值