该题目的要求是 判断str1和str2能否归并成为str3,递归的思路是正确的
bool helper(string &str_x,string &str_y,int x,int y){
while(x<str_x.size()&&y<str_y.size()){
if(str_x[x]==str_y[y]){
++x;
++y;
}
else{
return false;
}
}
if(x==str_x.size()&&y==str_y.size())
return true;
else
return false;
}
bool helper(string &str1,string &str2,string &str3,int m,int n,int k){
if(m==str1.size()){
return helper(str2,str3,n,k);
}
else if(n==str2.size()){
return helper(str1,str3,m,k);
}
else if(k==str3.size()){
return false;
}
else {
if(str1[m]==str3[k]&&str2[n]!=str3[k])
return helper(str1,str2,str3,m+1,n,k+1);
else if(str1[m]!=str3[k]&&str2[n]==str3[k])
return helper(str1,str2,str3,m,n+1,k+1);
else
return helper(str1,str2,str3,m+1,n,k+1)||helper(str1,str2,str3,m,n+1,k+1);
}
}
int main(){
int nums;
cin>>nums;
string str1,str2,str3;
for(int i=0;i<nums;++i){
cin>>str1>>str2>>str3;
int m=0,n=0,k=0;//m,n分别指向str1和str2的第0个元素
cout<<helper(str1,str2,str3,0,0,0)<<endl;
}
return 0;
}
下面附上原来的错误代码
int main(){//str1:bcf str2:acde str3:abcdcef
int nums;
cin>>nums;
string str1,str2,str3;
for(int i=0;i<nums;++i){
cin>>str1>>str2>>str3;
int m=0,n=0,k=0;//m,n分别指向str1和str2的第0个元素
bool flag=true;
while(m<str1.size()&&n<str2.size()&&k<str3.size()){
if(str1[m]==str3[k]){
++m;
++k;
}
else if(str2[n]==str3[k]){
++n;
++k;
}
else{
flag=false;
break;
}
}
while(m<str1.size()&&k<str3.size()){
if(str1[m]==str3[k]){
++m;
++k;
}
else{
flag=false;
break;
}
}
while(n<str2.size()&&k<str3.size()){
if(str2[n]==str3[k]){
++n;
++k;
}
else{
flag=false;
break;
}
}
if(m==str1.size()&&n==str2.size()&&k==str3.size())
cout<<flag<<endl;
else
cout<<0<<endl;
}
return 0;
}