首页 > 代码库 > Interleaving String

Interleaving String

https://leetcode.com/problems/interleaving-string/

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

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

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

这题有点类似于之前的求编辑距离的题:http://www.cnblogs.com/biyeymyhjob/archive/2012/09/28/2707343.html

定义f[i][j]为 以s1[0,i]s2[0,j]匹配s3[i][j] 

当j==0时,f[i][0]= f[i-1][0] && s1[i-1]==s3[i-1]

当i==0时,f[0][j]= f[0][j-1] && s2[j-1]==s3[j-1]

当i>=1&&j>=1时,f[i][j]= (f[i-1][j] && s1[i-1]==s3[i-1][j]) || (f[i][j-1] && s2[j-1]== s3[i][j-1])

bool isInterleave(string s1, string s2, string s3) {
        if(s3.length()!=s1.length()+s2.length())
           return false;
           
        vector<vector<bool>> f(s1.length()+1,vector<bool>(s2.length()+1,true));
        for(int i=1;i<=s1.length();i++)
           f[i][0]= f[i-1][0] && s1[i-1]==s3[i-1];
           
        for(int i=1;i<=s2.length();i++)
           f[0][i]=f[0][i-1] && s2[i-1]==s3[i-1];
           
        for(int i=1;i<=s1.length();i++)
        {
            for(int j=1;j<=s2.length();j++)
            {
                f[i][j]=(f[i-1][j] && s1[i-1]==s3[i+j-1]) || (f[i][j-1] && s2[j-1]==s3[i+j-1]);
            }
        }
        
        return f[s1.length()][s2.length()];
    }

 

Interleaving String