您的位置:首页 > 其它

[Lintcode] Interleaving String 交叉字符串

2016-10-10 23:23 363 查看
Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1and s2.

Have you met this question in a real interview? 

Yes

Example

For s1 = 
"aabcc"
, s2
"dbbca"

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

要求时间复杂度小于O(N×N)。分析:关于字符串比较的问题,可以考虑使用DP求解。这里可以使用二维DP。

res[i][j] 代表s1中前i个字符与s2中前j个字母是否可以交叉匹配成为s2中前i+j个字符。

公式为:

        if s3[i + j] = s1[i] = s2[j]. res[i][j] = res[i - 1][j] || res[i][j - 1]

        if s3[i + j] = s1[i] res[i][j] = res[i - 1][j] 

        if s3[i + j] = s2[j] res[i][j] = res[i][j - 1]

         else s3[i + j] = false;

初始条件是res[0][0] = true. 即s1前0个字符加s2前0个字符,可以拼凑成s3前0个字符。

public class Solution {
/**
* Determine whether s3 is formed by interleaving of s1 and s2.
* @param s1, s2, s3: As description.
* @return: true or false.
*/
public boolean isInterleave(String s1, String s2, String s3) {

if(s1.length() + s2.length() != s3.length()) return false;

boolean[][] res = new boolean[s1.length() + 1][s2.length() + 1];
res[0][0] = true;
for(int i = 1; i <= s1.length(); i++)
res[i][0] = res[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1);
for(int j = 1; j <= s2.length(); j++)
res[0][j] = res[0][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1);
for(int i = 1; i <= s1.length(); i++) {
for(int j = 1; j <= s2.length(); j++) {
if(s3.charAt(i + j - 1) == s1.charAt(i - 1) &&
s3.charAt(i + j - 1) == s2.charAt(j - 1)) {
res[i][j] = res[i - 1][j] || res[i][j - 1];
} else if (s3.charAt(i + j - 1) == s1.charAt(i - 1)) {
res[i][j] = res[i - 1][j];
} else if (s3.charAt(i + j - 1) == s2.charAt(j - 1)) {
res[i][j] = res[i][j - 1];
} else
res[i][j] = false;
}
}

return res[s1.length()][s2.length()];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  lintcode