利用动态规划解决交叉字符串问题

给出三个字符串:s1、s2、s3,判断s3是否由s1和s2交叉构成。

比如 s1 = "aabcc" s2 = "dbbca"

    - 当 s3 = "aadbbcbcac",返回  true.

    - 当 s3 = "aadbbbaccc", 返回 false.

利用动态规划,通过容器构造数组,其实现代码如下,

#include<iostream>
#include<string>
#include<vector>
using namespace std;
bool isInterleave(const string &s1, const string &s2, const string &s3) 
{
	if (s3.length() != s1.length() + s2.length())//检查长度是否匹配
	{
		return false;
	}
	if (s2.length() == 0)//特例情况1
	{
		return s1 == s3;
	}
	if (s1.length() == 0)//特例情况2
	{
		return s2 == s3;
	}
	//初始化二维矩阵((m+1)*(n+1)),全部为0
	vector<vector<bool>> dp(s1.length() + 1, vector<bool>(s2.length() + 1, false));
	dp[0][0] = true;
	for (int i = 1; i != s1.length() + 1; ++i)
	{
		dp[i][0] = dp[i - 1][0] && (s1[i - 1] == s3[i - 1]);
	}
	for (int j = 1; j != s2.length() + 1; ++j)
	{
		dp[0][j] = dp[0][j - 1] && (s2[j - 1] == s3[j - 1]);
	}
	for (int i = 1; i != s1.length() + 1; ++i)
	{
		for (int j = 1; j != s2.length() + 1; ++j)
		{
			dp[i][j] = ((dp[i - 1][j] && s1[i - 1] == s3[i + j - 1]) || (dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]));
		}
	}
	return dp[s1.length()][s2.length()];
}
int main()
{
	string s1 = "aabcc";
	string s2 = "dbbca";
	string s3 = "aadbbcbcac";
	string s4 = "aadbbbaccc";
	string s5 = "anagl";
	cout << boolalpha <<isInterleave(s1, s2, s3) << endl;
	cout << boolalpha <<isInterleave(s1, s2, s4) << endl;
	cout << boolalpha<< isInterleave(s1, s2, s5) << endl;
	system("pause");
	return 0;
}

实验结果如下图所示,

利用动态规划解决交叉字符串问题_第1张图片

你可能感兴趣的:(C++,String,动态规划)