24. Interleaving String

Link to the problem

Description

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

Example

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

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

Idea

Use dynamic programming, for s1[:i] and s2[:j], we can check if they can be interleaved to s3[:i + j] by asking s1[:i - 1], s2[:j], and s1[:i], s2[:j - 1]. Space can be optimized by storing two rolling rows.

Solution

class Solution {
public:
    bool isInterleave(string s1, string s2, string s3) {
        int m = s1.size(), n = s2.size();
        if (s3.size() != m + n) return false;
        vector<bool> dp(n + 1, false);
        dp[0] = true;
        for (int j = 1; j <= n; ++j) {
            dp[j] = dp[j - 1] && s2[j - 1] == s3[j - 1];
        }
        for (int i = 1; i <= m; ++i) {
            vector<bool> dp2(n + 1, false);
            for (int j = 0; j <= n; ++j) {
                if (i && dp[j] && s1[i - 1] == s3[i + j - 1]) dp2[j] = true;
                if (j && dp2[j - 1] && s2[j - 1] == s3[i + j - 1]) dp2[j] = true;
            }
            dp = dp2;
        }
        return dp[n];
    }
};

101 / 101 test cases passed.
Runtime: 4 ms

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 14,354评论 0 33
  • 皮格马利翁。 “皮格马利翁是希腊神话中的塞浦路斯国王,善雕刻。他看遍塞浦路斯的凡间女子无一中意,决定永不纳妃立...
    司昀阅读 1,814评论 2 4
  • 先看效果 基于handler实现, 比timertask更省内存. values/attrs中 使用方法 xml中...
    sankemao阅读 2,910评论 0 0
  • 《得到》App 每日一字 三 王 下 英语进程 英语听写——85集 姑娘英语 粉红猪小妹第一季第二集 三遍 今日...
    Pheeb阅读 1,279评论 0 0

友情链接更多精彩内容