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

Interleaving String

时间:2015-03-31 16:08:55      阅读:106      评论:0      收藏:0      [点我收藏+]

标签:dp

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.

#include<iostream>
#include<vector>
#include<string>
using namespace std;

 bool isInterleave(string s1, string s2, string s3) {
	int m = s1.size();
	int n = s2.size();
	if (s3.size()!=m+n)
		return false;
	vector<vector<bool>>InterVector(m+1,vector<bool>(n+1,false));
	InterVector[0][0] = true;
	for (int i = 1;i!=m+1;++i)
	{
		if (s3[i-1]==s1[i-1])
			InterVector[i][0] = true;
		else
			break;
	}
	for (int j = 1;j!=n+1;++j)
	{
		if (s3[j-1]==s2[j-1])
			InterVector[0][j] = true;
		else
			break;
	}
	for (int i = 1;i!=m+1;++i){
		char c1 = s1[i-1];
		for (int j = 1;j!=n+1;++j)
		{
			char c2 = s2[j-1];
			char c3 = s3[i+j-1];
			if (c1==c3)
				InterVector[i][j] = InterVector[i-1][j];
			if (c2==c3)
				InterVector[i][j] = InterVector[i][j-1]||InterVector[i][j];
		}
	}
	return InterVector[m][n];
 }


 

Interleaving String

标签:dp

原文地址:http://blog.csdn.net/li_chihang/article/details/44779469

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