题目:输入两个字符串,比如abdbcc和abc,输出第二个字符串在第一个字符串中的连接次序,即输出125,126,145,146
//解法一:
#include<vector>
#include<iostream>
#include<string>
using namespace std;
void PrintArray(string PString,string SString,int pIndex,int sIndex,int printIndex,vector<int> outArray);
int main()
{
string ParString,SonString;
cin>>ParString>>SonString;
if(ParString.size()==0||SonString.size()==0)
return 0;
vector<int> outArray(3,0);
PrintArray(ParString,SonString,0,0,0,outArray);
return 0;
}
void PrintArray(string PString,string SString,int pIndex,int sIndex,int printIndex,vector<int> outArray)
{
int pLen=PString.size();
int sLen=SString.size();
int pStart=pIndex;
int sStart=sIndex;
int printNum=printIndex;
if(printNum==sLen)
{
for(int i=0;i<sLen;++i)
cout<<outArray[i];
cout<<endl;
return;
}
for(int i=pStart;i<pLen;++i)
{
for(int j=sStart;j<sLen;++j)
{
if(PString[i]==SString[j])
{
outArray[printNum]=i+1;
//不能直接将pStart=i+1;这样会将当前递归层次中的pStart更改,导致字符遍历出问题
pStart=i;
sStart=j;
//递归处理接下来的字符
PrintArray(PString,SString,pStart+1,sStart+1,printNum+1,outArray);
}
}
}
}
//解法二:
#include <iostream>
#include<string.h>
#include<list>
using namespace std;
list<int>list1;
void findLink(const char*p1,const char*p2,int i,int j)
{
if(!p1[i]||!p2[j])
return ;
if(p2[j]==p1[i]&&!p2[j+1])
{
for(list<int>::iterator it=list1.begin();it!=list1.end();it++)
{
cout<<*it<<" ";
}
cout<<i+1<<endl;
}
if(p1[i]==p2[j])
{
list1.push_back(i+1);
findLink(p1,p2,i+1,j+1);
list1.pop_back();
}
findLink(p1,p2,i+1,j);
}
int main() {
char p[10]="abdbccd";
char q[10]="abc";
findLink(p,q,0,0);
return 0;
}