leecode97. Interleaving String

18 篇文章 0 订阅

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
具体思路:一个类型为bool型的table数组table[i][j],代表从str1前i个元素和str2前j个元素构成长度为i+j的str3 //此时,i和j都代表长度,再转换为下标时要注意-1,当然可以一开始就令i为str1第i个元素参与,只不过相较于后者,前者更易理解 初始化先不说 接下来就是状态方程 table[i][j] = (table[i-1][j] && s1[i-1] == s3[i+j-1] ) || (table[i][j-1] && s2[j-1] == s3[i+j-1] )
从str1取第i-1个元素(因为i代表前i个)str2还是j个不变。构成str3共i+j个,也就是str3[i+j-1],此时成立条件有两个 一个时s1[i-1] == s3[i+j-1] 另一个就是table[i-1][j]为true 同理可以从str2取


bool isInterleave(string s1, string s2, string s3) { if(s3.length() != s1.length() + s2.length()) return false; bool table[s1.length()+1][s2.length()+1]; for(int i=0; i<s1.length()+1; i++) for(int j=0; j< s2.length()+1; j++){ if(i==0 && j==0) table[i][j] = true; else if(i == 0) table[i][j] = ( table[i][j-1] && s2[j-1] == s3[i+j-1]); else if(j == 0) table[i][j] = ( table[i-1][j] && s1[i-1] == s3[i+j-1]); else table[i][j] = (table[i-1][j] && s1[i-1] == s3[i+j-1] ) || (table[i][j-1] && s2[j-1] == s3[i+j-1] ); } return table[s1.length()][s2.length()];}

Here is some explanation:

DP table represents if s3 is interleaving at (i+j)th position when s1 is at ith position, and s2 is at jth position. 0th position means empty string.

So if both s1 and s2 is currently empty, s3 is empty too, and it is considered interleaving. If only s1 is empty, then if previous s2 position is interleaving and current s2 position char is equal to s3 current position char, it is considered interleaving. similar idea applies to when s2 is empty. when both s1 and s2 is not empty, then if we arrive i, j from i-1, j, then if i-1,j is already interleaving and i and current s3 position equal, it s interleaving. If we arrive i,j from i, j-1, then if i, j-1 is already interleaving and j and current s3 position equal. it is interleaving.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值