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.

class Solution {
public:
bool isInterleave(string s1, string s2, string s3) {
int l1 = s1.size(), l2 = s2.size(), i, j;
if(l1 + l2 != s3.size())
return false;
vector<vector<bool>> isMatch(l1+, vector<bool>(l2+, false));
isMatch[][] = true;
for(i = ; i <= l1; i++)
{
if(s1[i-] == s3[i-])
isMatch[i][] = true;
else
break;
}
for(i = ; i <= l2; i++)
{
if(s2[i-] == s3[i-])
isMatch[][i] = true;
else
break;
}
for(i = ; i <= l1; i++)
{
for(j = ; j <= l2; j++)
{
isMatch[i][j] = ((s1[i-] == s3[i+j-]) && isMatch[i-][j]) || ((s2[j-] == s3[i+j-]) && isMatch[i][j-]);
}
}
return isMatch[l1][l2];
}
};

Considering:

s1 = a1, a2 ........a(i-1), ai
s2 = b1, b2, .......b(j-1), bj
s3 = c1, c3, .......c(i+j-1), c(i+j)

Defined

match[i][j] means s1[0..i] and s2[0..j] is matched S3[0..i+j]

So, if ai == c(i+j), then match[i][j] = match[i-1][j], which means

s1 = a1, a2 ........a(i-1)
s2 = b1, b2, .......b(j-1), bj
s3 = c1, c3, .......c(i+j-1)

Same, if bj = c(i+j), then match[i][j] = match[i][j-1];

Formula:

Match[i][j] =
(s3[i+j-1] == s1[i]) && match[i-1][j] ||
(s3[i+j-1] == s2[j]) && match[i][j-1]

Initialization:

i=0 && j=0, match[0][0] = true;

i=0, s3[j] == s2[j], match[0][j] |= match[0][j-1]
s3[j] != s2[j], match[0][j] = false;

j=0, s3[i] == s1[i], match[i][0] |= match[i-1][0]
s3[i] != s1[i], Match[i][0] = false;

最新文章

  1. windows phone如何才能在中国翻身?
  2. hibernate执行session.createQuery(hql)时hql若有参数则报错
  3. sprint5.0
  4. IMetadataAware接口的特性定制Model元数据
  5. JVM系列二:GC策略&amp;内存申请、对象衰老
  6. Spring(3.2.3) - Beans(5): 集合属性的注入
  7. Postfix 电子邮件系统精要
  8. Table显示滚动条
  9. Java GC 日志详解(转)
  10. javascript 学习随笔6
  11. jquery新窗口打开链接
  12. VUE-脚手架搭建
  13. [Luogu3041][USACO12JAN]视频游戏的连击Video Game Combos
  14. 审计篇丨PHPcms9.6.3后台XSS审计
  15. Anniversary party POJ - 2342 (树形DP)
  16. ajax 的json格式
  17. 如何自定义一个组件loading
  18. binlog开启和查看
  19. MFCC
  20. UVA12888 【Count LCM】(莫比乌斯反演)

热门文章

  1. Scanline Fill Algorithm
  2. python tensorflow keras
  3. scrapy爬虫系列之三--爬取图片保存到本地
  4. Linux内核之vmlinux与vmlinuz
  5. [Err]1418 This function has none of DETERMINISTIC,NO SQL,or R
  6. KS检验学习[转载]
  7. Keras实践:模型可视化
  8. rails常用gem
  9. Mail.Ru Cup 2018 Round 2 Solution
  10. zwPython,字王集成式python开发平台,比pythonXY更强大、更方便。