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

LeetCode Interleaving String

时间:2015-04-25 00:20:01      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:

Given s1s2s3, 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。

思路:DP去做,dp[i+1][j+1]表示s1[0...i]和s2[0...j]是否能拼成s3[i+j+1],那么在dp[i][j+1]=true的情况下,只要s1[i+1]=s3[i+j+1]的话,那么dp[i+1][j+1]就满足,同样dp[i+1][j]的情况也是一样的。


public class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
        int m = s1.length(), n = s2.length();
    	if (m + n != s3.length()) return false;
    	
    	boolean dp[][] = new boolean[m+1][n+1];
    	dp[0][0] = true;
    	for (int i = 0; i < n; i++) 
    		dp[0][i+1] = dp[0][i] && (s2.charAt(i) == s3.charAt(i));
    	for (int i = 0; i < m; i++)
    		dp[i+1][0] = dp[i][0] && (s1.charAt(i) == s3.charAt(i));
    	
    	for (int i = 0; i < m; i++)
    		for (int j = 0; j < n; j++)
    			dp[i+1][j+1] = (dp[i][j+1] && (s1.charAt(i) == s3.charAt(i+j+1)) ||
    					(dp[i+1][j] && (s2.charAt(j) == s3.charAt(i+j+1))));
    	
    	return dp[m][n];
    }
}




LeetCode Interleaving String

标签:

原文地址:http://blog.csdn.net/u011345136/article/details/45252915

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