数据结构基础(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 *> ¤t_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;
}
}