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

LeetCode:Interleaving String

时间:2015-05-19 19:14:56      阅读:117      评论: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.


思路分析:设s2的长度为length2,s1的长度为length1。开一个(length2+1)*(length1+1)的bool数组flag。flag[i][j]表示字符串s1+i和字符串s2+j能否构造s3+i+j。首先初始化二维数组的最后一列和最后一行,根据状态转移方程来求得flag[0][0],即得结果。


代码:

class Solution
{
	public:
		bool isInterleave(string s1,string s2,string s3)
		{
			int index1 = 0,index2 = 0,index3 = 0;
			int length1 = s1.length();
			int length2 = s2.length();
			int length3 = s3.length();

			if((length1 + length2) != length3)
				return false;

			if(length1 == 0)
				return s2 == s3;

			if(length2 == 0)
				return s1 == s3;

			//生成一个(length2+1)*(length1+1)的bool数组
			vector<vector<bool>> flag;
			for(int i = 0;i < (length2 + 1);i++)
			{
				vector<bool> temp(length1+1,false);
				flag.push_back(temp);
			}

			//初始化最后一列
			for(int i = length2 - 1;i >= 0;i--)
			{
				if(s2[i] == s3[length1 + i])
					flag[i][length1] = true;
				else
					break;
			}

			//初始化最后一行
			for(int i = length1 - 1;i >= 0;i--)
			{
				if(s1[i] == s3[length2 + i])
					flag[length2][i] = true;
				else
					break;
			}

			for(int i = length2 - 1;i >= 0;i--)
				for(int j = length1 - 1;j >= 0;j--)
				{
					if(s1[j] == s3[i + j])
						if(flag[i][j+1])
						{
							flag[i][j] = true;
							continue;
						}
					if(s2[i] == s3[i + j])
						if(flag[i+1][j])
						{
							flag[i][j] = true;
							continue;
						}
				}
			return flag[0][0];
		}
};


LeetCode:Interleaving String

标签:

原文地址:http://blog.csdn.net/yao_wust/article/details/45846427

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