检查一个字符串是否被另外两个字符串交错

时间:2015-10-25 05:38:12

标签: c++ algorithm

我正在调试以下问题。发布详细的问题陈述和编码。我的问题是,是否(else if (A[i-1]==C[i+j-1] && B[j-1]==C[i+j-1]))是否必要的最后一个?我认为没有必要,因为它始终由else if(A[i-1]==C[i+j-1] && B[j-1]!=C[i+j-1])覆盖,或由else if (A[i-1]!=C[i+j-1] && B[j-1]==C[i+j-1])覆盖,即前两个if-else检查条件。感谢。

给定s1,s2,s3,找出s3是否由s1和s2的交织形成。

例如, 鉴于: s1 =" aabcc", s2 =" dbbca",

当s3 =" aadbbcbcac"时,返回true。 当s3 =" aadbbbaccc"时,返回false。

// The main function that returns true if C is
// an interleaving of A and B, otherwise false.
bool isInterleaved(char* A, char* B, char* C)
{
    // Find lengths of the two strings
    int M = strlen(A), N = strlen(B);

    // Let us create a 2D table to store solutions of
    // subproblems.  C[i][j] will be true if C[0..i+j-1]
    // is an interleaving of A[0..i-1] and B[0..j-1].
    bool IL[M+1][N+1];

    memset(IL, 0, sizeof(IL)); // Initialize all values as false.

    // C can be an interleaving of A and B only of sum
    // of lengths of A & B is equal to length of C.
    if ((M+N) != strlen(C))
       return false;

    // Process all characters of A and B
    for (int i=0; i<=M; ++i)
    {
        for (int j=0; j<=N; ++j)
        {
            // two empty strings have an empty string
            // as interleaving
            if (i==0 && j==0)
                IL[i][j] = true;

            // A is empty
            else if (i==0 && B[j-1]==C[j-1])
                IL[i][j] = IL[i][j-1];

            // B is empty
            else if (j==0 && A[i-1]==C[i-1])
                IL[i][j] = IL[i-1][j];

            // Current character of C matches with current character of A,
            // but doesn't match with current character of B
            else if(A[i-1]==C[i+j-1] && B[j-1]!=C[i+j-1])
                IL[i][j] = IL[i-1][j];

            // Current character of C matches with current character of B,
            // but doesn't match with current character of A
            else if (A[i-1]!=C[i+j-1] && B[j-1]==C[i+j-1])
                IL[i][j] = IL[i][j-1];

            // Current character of C matches with that of both A and B
            else if (A[i-1]==C[i+j-1] && B[j-1]==C[i+j-1])
                IL[i][j]=(IL[i-1][j] || IL[i][j-1]) ;
        }
    }

    return IL[M][N];
}
提前谢谢, 林

1 个答案:

答案 0 :(得分:2)

当C中的下一个字符与A和B中的下一个字符匹配时,您需要使用最终else if来捕获案例。例如,使用A="aaaa",{{1}运行您的程序}和B="aaaa"并查看您是否输入了最后一个C="aaaaaaaa"块。

此外,您还需要一个最终else if块来处理以前的条件都不匹配的情况。在这种情况下,您需要将else设置为IL[i][j]。否则,该函数将错误地返回false

编辑:即使代码使用true初始化memsetIL的所有元素,它也可能无效,因为ISO C++ does not support可变长度数组(VLA)。事实上,这就是我tried the code at cpp.sh时发生的事情。它使用带有标志的g ++ - 4.9.2,导致它报告0sizeof(IL),即使1应该支持VLA。也许这是一个编译器错误,或者它可能不支持多维VLA。无论如何,根本不使用它们可能更安全。

相关问题