Interleaving String

来源:互联网 发布:photoshop最新软件版本 编辑:程序博客网 时间:2024/06/03 15:49

Given s1, s2, s3, find whether s3 is formed by the interleaving ofs1 and s2.

For example,
Given:
s1 = "aabcc",
s2 = "dbbca",

When s3 = "aadbbcbcac", return true.
When s3 = "aadbbbaccc", return false.

class Solution {public:    bool isInterleave(string s1, string s2, string s3) {        int m = s1.length();        int n = s2.length();        int k = s3.length();        if (m+n != k)        {            return false;        }        bool **buf = new bool*[m+1];        for (int i = 0; i <= m; i++)        {            buf[i] = new bool[n+1];        }        buf[0][0] = true;        for (int i = 1; i <= m; i++)        {            buf[i][0] = buf[i-1][0] && s1[i-1] == s3[i-1];        }        for (int i = 1; i <= n; i++)        {            buf[0][i] = buf[0][i-1] && s2[i-1] == s3[i-1];        }        for (int i = 1; i <= m; i++)        {            for (int j = 1; j <= n; j++)            {                buf[i][j] = (buf[i-1][j] && s1[i-1] == s3[i+j-1]) || (buf[i][j-1] && s2[j-1] == s3[i+j-1]);            }        }        bool result = buf[m][n];        for (int i = 0; i <= m; i++)        {            delete []buf[i];        }        delete []buf;        return result;    }};


0 0