97. Interleaving String
发布日期:2021-05-09 02:50:43 浏览次数:17 分类:博客文章

本文共 1444 字,大约阅读时间需要 4 分钟。

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

Example 1:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbcbcac"Output: true

Example 2:

Input: s1 = "aabcc", s2 = "dbbca", s3 = "aadbbbaccc"Output: false

 

Approach #1: DP. [C++]

class Solution {public:    bool isInterleave(string s1, string s2, string s3) {        //if (s1 == "" && s2 == "" && s3 == "") return true;        //if (s1 == "" || s2 == "" || s3 == "") return false;        if (s1.length() + s2.length() != s3.length()) return false;                vector
> match(s1.length()+1, vector
(s2.length()+1, false)); match[0][0] = true; for (int idx = 0; idx < s1.length() + s2.length(); ++idx) { for (int s1Len = 0; s1Len <= idx+1 && s1Len <= s1.length(); ++s1Len) { int s2Len = idx + 1 - s1Len; if (s2Len > s2.length()) continue; if ((s1Len > 0 && match[s1Len-1][s2Len] && s3[idx] == s1[s1Len-1]) || (s2Len > 0 && match[s1Len][s2Len-1] && s3[idx] == s2[s2Len-1])) match[s1Len][s2Len] = true; } } return match[s1.length()][s2.length()]; }};

������

Analysis:

status: match[s1Len][s2Len] represent s1Len characters in s1 and s2Len characters in s2 wether match with s1Len+s2Len characters in s3.

init: match[0][0] = true;

func: 

result: match[s1.length()][s2.length()].

 

上一篇:115. Distinct Subsequences
下一篇:96. Unique Binary Search Trees

发表评论

最新留言

不错!
[***.144.177.141]2025年04月23日 01时03分28秒