判断字符串interleave

来源:互联网 发布:2g网络关闭 编辑:程序博客网 时间:2024/06/07 06:34

问题描述:给定三个字符串str1、str2和str,判断str是否为str1和str2的interleave。如str1="abc",str2="def",str="adbecf",那么str就是str1和str2的interleave。即str中包含str1和str2中的所有字符,且str1和str2中的字符在str中的相对顺序没变,如str1中'a'在'b'前,'b'在'c'前,在str中虽然'a'和'b','b'和'c'不相连,但仍然保持'a'在'b'前,'b'在'c'前的相对顺序。

算法思路:递归算法

C++代码如下:

#include<iostream>using namespace std;bool isinterleave(char* str1,char* str2,char* mixed_str){    if(*str1=='\0'&&*str2=='\0'&&*mixed_str=='\0')        return true;    if(*str1==*str2&&*str1==*mixed_str)    {        bool result_one=false;        bool result_two=false;        result_one=isinterleave(str1+1,str2,mixed_str+1);        result_two=isinterleave(str1,str2+1,mixed_str+1);        if(!result_one&&!result_two)            return false;        else            return true;    }    else if(*str1==*mixed_str&&*str1!=*str2)        return isinterleave(str1+1,str2,mixed_str+1);    else if(*str2==*mixed_str&&*str1!=*str2)        return isinterleave(str1,str2+1,mixed_str+1);    else        return false;}int main(){    char str1[100];    char str2[100];    char str3[100];    scanf("%s",str1);    scanf("%s",str2);    scanf("%s",str3);    if(isinterleave(str1,str2,str3))        cout<<"yes!"<<endl;    else        cout<<"no!"<<endl;    return 0;}


 

原创粉丝点击