NO.97 staggered string

Given three strings s1, s2, s3, s3 verify interleaved by s1 and s2 thereof.

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"
Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"
Output: false

bool isInterleave(char * s1, char * s2, char * s3){
    int len1=strlen(s1);
    int len2=strlen(s2);
    int len3=strlen(s3);
    if(len1+len2!=len3)return false;
    bool ** state=(bool **)malloc(sizeof(bool *)*(len2+1));
    for(int i=0;i<len2+1;i++)
    {
        state[i]=(bool *)calloc(len1+1,sizeof(bool));
    }
    state[0][0]=true;
    for(int i=1;i<=len2;i++)
    {
        state[i][0]=state[i-1][0]&&s2[i-1]==s3[i-1];
    }
    for(int i=1;i<=len1;i++)
    {
        state[0][i]=state[0][i-1]&&s1[i-1]==s3[i-1];
    }
    for(int i=1;i<=len2;i++)
    {
        for(int j=1;j<=len1;j++)
        {
            state[i][j]=(state[i-1][j]&&s2[i-1]==s3[i+j-1])||(state[i][j-1]&&s1[j-1]==s3[i+j-1]);
        }
    }
    bool ret=state[len2][len1];
    for(int i=0;i<len2+1;i++)
    {
        free(state[i]);
    }
    free(state);
    return ret;
}

When execution: 8 ms, beat the 85.71% of users Interleaving String submission of C

Memory consumption: 7.1 MB, defeated 12.50% of users Interleaving String submission of C

Guess you like

Origin blog.csdn.net/xuyuanwang19931014/article/details/91362318