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

Leetcode-Interleaving String

时间:2014-11-24 06:25:09      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   for   on   div   

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.

Analysis:

Initially, we consider the state d[k,i,j] as whether the first k chars in s3 is the interleaving string of the first i chars of s1 and the first j chars of s2. We then have the formula:

d[k,i,j] = d[k-1][i-1][j] && s3[k]==s1[i]  || d[k-1][i][j-1] && s3[k]==s2[j].

We then find that since a state d[k,i,j] has meaning only when k==(i+j), we actaully can reduce the number of states. We further use the state d[i,j] to present whether the s1[0-(i-1)] and s2[0-(j-1)] can interleave to s3[0-(i+j-1)]. we have formula:

d[i][j] = d[i-1][j] && s3[i+j-1]==s1[i-1]    ||   d[i][j-1] && s3[i+j-1]==s2[j-1].

Solution:

 1 public class Solution {
 2     public boolean isInterleave(String s1, String s2, String s3) {
 3         int len1 = s1.length();
 4         int len2 = s2.length();
 5         
 6         //NOTE: need to consider this boundary case!
 7         if (s3.length()!=len1+len2) return false;
 8         
 9         boolean[][] d = new boolean[len1+1][len2+1];
10         d[0][0]=true;
11         for (int i=1;i<=len2;i++)
12             if (d[0][i-1] && s2.charAt(i-1)==s3.charAt(i-1))
13                 d[0][i]=true;
14             else d[0][i]=false;
15 
16         for (int i=1;i<=len1;i++)
17             if (d[i-1][0] && s1.charAt(i-1)==s3.charAt(i-1))
18                 d[i][0]=true;
19             else d[i][0]=false;
20 
21         for (int i=1;i<=len1;i++)
22             for (int j=1;j<=len2;j++)
23                 if (d[i-1][j] && s1.charAt(i-1)==s3.charAt(i+j-1))
24                     d[i][j]=true;
25                 else if (d[i][j-1] && s2.charAt(j-1)==s3.charAt(i+j-1))
26                     d[i][j]=true;
27                 else d[i][j]=false;
28 
29 
30         return d[len1][len2];        
31     }
32 }

 

Leetcode-Interleaving String

标签:style   blog   io   ar   color   sp   for   on   div   

原文地址:http://www.cnblogs.com/lishiblog/p/4117856.html

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