97. Interleaving String
2017-11-29 18:45
197 查看
题目:
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.
判断S1、S2是否能交替的组成S3.
可以用动态规划解决。
定义一个数组:boolean[][] DP=new boolean[s2Length+1][s1Length+1];
DP[i][j]=TRUE表示,字符串S2前i个字符、字符串S1前j个字符可以交替组成S3前i=j-1个字符.
初始状态:DP[0][0]=true;
状态转移方程:
1.if (DP[i-1][j] && s3.charAt(i+j-1)==s2.charAt(i-1)){ DP[i][j]=true; } 2.if(DP[i][j-1] && s3.charAt(i+j-1)==s1.charAt(j-1)){ DP[i][j]=true; }
第一条方程:若DP[i-1][j]=TRUE即DP[i][j]=TRUE表示,字符串S2前i-1个字符、字符串S1前j个字符可以交替组成S3前i=j-1个字符。此时若S2的第i个字符与S3的第i+j-1个字符相等,DP[i][j]=TRUE。否则DP[i][j]=false。
第二条方程同理。
public boolean isInterleave(String s1, String s2, String s3) { if(s1.length()+s2.length()!=s3.length()) return false; int s1Length=s1.length(); int s2Length=s2.length(); boolean[][] DP=new boolean[s2Length+1][s1Length+1]; DP[0][0]=true; for(int i=1;i<s1Length+1;i++){ DP[0][i]=DP[0][i-1]&&(s1.charAt(i-1)==s3.charAt(i-1)); } for(int j=1;j<s2Length+1;j++){ DP[j][0]=DP[j-1][0]&&(s2.charAt(j-1)==s3.charAt(j-1)); } for(int i=1;i<s2Length+1;i++){ for(int j=1;j<s1Length+1;j++){ if (DP[i-1][j] && s3.charAt(i+j-1)==s2.charAt(i-1)){ DP[i][j]=true; } if(DP[i][j-1] && s3.charAt(i+j-1)==s1.charAt(j-1)){ DP[i][j]=true; } } } return DP[s2Length][s1Length]; }
相关文章推荐
- 97. Interleaving String
- LeetCode 97: Interleaving String 字符串交错
- FTPrep, 97 Interleaving String
- 97/100 Interleaving String/Same Tree
- 97. Interleaving String
- 【leetcode】String——Interleaving String(97)
- 97. Interleaving String
- 97. Interleaving String
- Leetcode 97 Interleaving String
- 97. Interleaving String
- 97. Interleaving String
- 97. Interleaving String
- 97. Interleaving String
- leetcode[97]Interleaving String
- Leetcode-97 Interleaving String
- 97. Interleaving String
- leetcode_[python/C++]_97_Interleaving String_动态规划
- Leetcode 97, Interleaving String
- 97.Interleaving String
- 97. Interleaving String