Leetcode Interleaving String

来源:互联网 发布:学淘宝美工多少钱 编辑:程序博客网 时间:2024/06/06 15:02

Given s1, s2, s3, find whethers3 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.


看到题目的时候,依然最先想到了最直接脑残的穷举法,发现情况很难处理。然后遇到这种情况就想起了传说中的动态规划大法,不得不说,动态规划大法真是好。


动态规划方程:

len1为s1的长度,len2为s2的长度

通过题意,将动态规划方程设为二维数组。关于数组的大小,因为我们需要初始状态,所以动态规划方程的大小为dp[len1+1][len2+1],dp[0][0] = true;

当i==0,  dp[i][j] = dp[i][j-1] && (s3[i+j-1] == s2[j-1])

当j==0,dp[i][j] = dp[i-1][j] && (s3[i+j-1] == s1[i-1]);

其他情况,dp[i][j] = (dp[i-1][j] && (s3[i+j-1] == s1[i-1])) || (dp[i][j-1] && (s3[i+j-1] == s2[j-1]));


代码如下:

class Solution {public:    bool isInterleave(string s1, string s2, string s3) {        int len1 = s1.length(),len2 = s2.length(),len3=s3.length();                if(len1+len2 != len3)            return false;                    bool dp[len1+1][len2+1];        for(int i=0;i<len1+1;i++)        {            for(int j = 0;j<len2+1;j++)            {                if(i==0 && j==0)                    dp[i][j] = true;                else if(i==0)                    dp[i][j] = dp[i][j-1] && (s3[i+j-1] == s2[j-1]);                else if(j==0)                    dp[i][j] = dp[i-1][j] && (s3[i+j-1] == s1[i-1]);                else                     dp[i][j] = (dp[i-1][j] && (s3[i+j-1] == s1[i-1])) || (dp[i][j-1] && (s3[i+j-1] == s2[j-1]));            }        }        return dp[len1][len2];    }};