码迷,mamicode.com
首页 > 其他好文 > 详细

Interleaving String [leetcode] DP

时间:2014-09-28 00:41:51      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:leetcode

dp[k1][k2]:s1[0...k1-1]和s2[0...k2-1]能否合成s3[0...k1 + k2 - 1]

    bool isInterleave(string s1, string s2, string s3) {
        if (s3.size() != s1.size() + s2.size()) return false;
        vector<vector<bool>> dp(s1.size() + 1);
        for (int i = 0; i < dp.size(); i++)
            dp[i] = vector<bool>(s2.size() + 1);
        dp[0][0] = true;//s1[0...k1-1]和s2[0...k2-1]能否合成s3[0...k1 + k2 - 1]
        for (int k1 = 0; k1 <= s1.size(); k1++)
        {
            for (int k2 = 0; k2 <= s2.size(); k2++)
            {
                if (k1 > 0)
                    dp[k1][k2] = dp[k1][k2] || (dp[k1 - 1][k2] && s1[k1 - 1] == s3[k1 + k2 - 1]);
                if (k2 > 0)
                    dp[k1][k2] = dp[k1][k2] || (dp[k1][k2 - 1] && s2[k2 - 1] == s3[k1 + k2 - 1]);
            }
        }
        return dp[s1.size()][s2.size()];
    }


Interleaving String [leetcode] DP

标签:leetcode

原文地址:http://blog.csdn.net/peerlessbloom/article/details/39620121

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!