您的位置:首页 > 其它

【leetcode】Interleaving String

2015-08-19 17:34 183 查看
from:https://leetcode.com/problems/interleaving-string/

Given s1, s2, s3, 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.

思路:

DP:



dp[a][b]意义,sa[0:a]与sb[0:b]是否能构成s[0:a+b]相等。(左开右闭)

例如,dp[1][0]= true,表示sa中子串“a”和b中“”可以构成s中“a”相等。

dp[1][1],表示“a”与“d”是否能表示成“aa”。

递推公式:

对于k=a+b,

(1)当sa[a-1]=s[k-1],那么dp[a][b] = dp[a][b] || dp[a-1][b]

(2)当sb[b-1]=s[k-1],那么dp[a][b] = dp[a][b] || dp[a][b-1]

对于(1),当sa中的字符对应了当前的s中的字符,那么dp[a][b]与dp[a][b-1]无关,因为对于s[0,a+b],只能由s[0, a+b-1]和一个sa中字符或者sb中字符匹配,如果选择了s[0,a+b]选择与sa[a-1]中字符匹配,那么其之前的s[0,
a+b-1]必然没有选择sa[a-1]。

public class Solution {
public boolean isInterleave(String sa, String sb, String s) {
int la=sa.length(), lb=sb.length(), ls=s.length();
if(la + lb != ls) {
return false;
}
boolean[][] dp = new boolean[la+1][lb+1];
dp[0][0] = true;
for(int a=1; a<=la; ++a) {
if(sa.charAt(a-1) == s.charAt(a-1)) dp[a][0] = true;
else break;
}
for(int b=1; b<=lb; ++b) {
if(sb.charAt(b-1) == s.charAt(b-1)) dp[0][b] = true;
else break;
}

for(int a=1; a<=la; ++a) {
for(int b=1; b<=lb; ++b) {
int k = a+b;
if(sa.charAt(a-1) == s.charAt(k-1)) dp[a][b] = dp[a-1][b] || dp[a][b];
if(sb.charAt(b-1) == s.charAt(k-1)) dp[a][b] = dp[a][b-1] || dp[a][b];
}
}
return dp[la][lb];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: