码迷,mamicode.com
首页 > 其他好文 > 详细

Interleaving String (DP)

时间:2016-04-18 20:19:25      阅读:143      评论:0      收藏:0      [点我收藏+]

标签:

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.

State:f[i][j]  表示s1的前i 个字符 和 s2的前j 个字符能组成s3的前 i + j 个字符

Function: if (((s1.charAt(i - 1) == s3.charAt(i + j - 1) && interleave[i - 1][j])) || (s2.charAt(j - 1) == s3.charAt(i + j - 1) && interleave[i][j - 1])) {
                    interleave[i][j] = true;

Initializtion:f[0][0] = true    f[i][0]  i = (1 ~ s1.length() )  f[0][j]  j = (1 ~ s2.length())

Answer:f[s1.length()][s2.length()]

 1 public class Solution {
 2     public boolean isInterleave(String s1, String s2, String s3) {
 3         if (s1.length() + s2.length() != s3.length()) {
 4             return false;
 5         }
 6         
 7         boolean[][] interleave = new boolean[s1.length() + 1][s2.length()  + 1];
 8         interleave[0][0] = true;
 9         for (int i = 1; i <= s1.length(); i++) {
10             if (s1.charAt(i - 1) == s3.charAt(i - 1) && interleave[i - 1][0]) {
11                 interleave[i][0] = true;
12             }
13         }
14         for (int i = 1; i <= s2.length(); i++) {
15             if (s2.charAt(i - 1) == s3.charAt(i - 1) && interleave[0][i - 1]) {
16                 interleave[0][i] = true;
17             }
18         }
19         
20         for (int i = 1; i <= s1.length(); i++) {
21             for (int j = 1; j <= s2.length(); j++) {
22                 if (((s1.charAt(i - 1) == s3.charAt(i + j - 1) && interleave[i - 1][j])) || (s2.charAt(j - 1) == s3.charAt(i + j - 1) && interleave[i][j - 1])) {
23                     interleave[i][j] = true;
24                 }
25             }
26         }
27         return interleave[s1.length()][s2.length()];
28     }
29 }

 

Interleaving String (DP)

标签:

原文地址:http://www.cnblogs.com/FLAGyuri/p/5405628.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!