小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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,要求判定字符串s3是否由s1 和s2组合而成。(每个字符串中的字母相对顺序不可变)
开始看到题目,没有解决思路。参考网友的答案,发现解决题目的两种思路。
方法一:递归的思路,但是该方法对于大集合数据会出现TLE
方法二:动态规划的思路
根据字符串1和2,建立判定二维矩阵。

AC代码

class Solution {
public:
	/*方法一:递归实现,对大数据组会TLE*/
	bool isInterleave1(string s1, string s2, string s3) {
		int len1 = s1.length(), len2 = s2.length(), len3 = s3.length();

		if (len2 == 0)
			return s1 == s3;
		else if (len1 == 0)
			return s2 == s3;
		else if (len3 == 0)
			return len1 + len2 == 0;
		else
		{
			if (s1[0] == s3[0] && s2[0] != s3[0])
				return isInterleave1(s1.substr(1), s2, s3.substr(1));
			else if (s1[0] != s3[0] && s2[0] == s3[0])
				return isInterleave1(s1, s2.substr(1), s3.substr(1));
			else if (s1[0] == s3[0] && s2[0] == s3[0])
				return isInterleave1(s1.substr(1), s2, s3.substr(1)) || isInterleave(s1, s2.substr(1), s3.substr(1));
			else
				return false;
		}//else
	}

	/*方法二:二维动态规划*/
	bool isInterleave(string s1, string s2, string s3) {
		int len1 = s1.length(), len2 = s2.length(), len3 = s3.length();
		if (len1 + len2 != len3)
			return false;
		else if (len2 == 0)
			return s1 == s3;
		else if (len1 == 0)
			return s2 == s3;
		else if (len3 == 0)
			return len1 + len2 == 0;
		else
		{
			vector<vector<int>> dp(len1 + 1, vector<int>(len2 + 1, 0));
			dp[0][0] = 1;
			for (int i = 1; i <= len1; ++i)
			{
				if (s1[i - 1] == s3[i - 1])
					dp[i][0] = 1;
				else
					break;
			}//for

			for (int j = 1; j <= len2; ++j)
			{
				if (s2[j - 1] == s3[j - 1])
					dp[0][j] = 1;
				else
					break;
			}//for

			for (int i = 1; i <= len1; ++i)
			{
				for (int j = 1; j <= len2; ++j)
				{
					if (s1[i - 1] == s3[i + j - 1])
						dp[i][j] = dp[i - 1][j] || dp[i][j];
					if (s2[j - 1] == s3[i + j - 1])
						dp[i][j] = dp[i][j - 1] || dp[i][j];
				}//for
			}//for
			return dp[len1][len2] == 1;
		}//else
	}
};

  

GitHub测试程序源码

 

posted on 2015-12-26 13:57  Coding菌  阅读(407)  评论(0编辑  收藏  举报