5 字符串拼接作者: 赵晓鹏时间限制: 1S章节: 动态规划与贪心
输入说明 :
见问题描述。
输出说明 :
见问题描述。
输入范例 :
aaaaaaaaaab
aaaaaaaac
aaaaaaaaaacaaaaaaaab
输出范例 :
YES
aa_________aaaaaaaab
#include<iostream>
#include<vector>
using namespace std;
bool dp[6000][6000];
bool isInterleave(string s1, string s2, string s3) {
int len1 = s1.length();
int len2 = s2.length();
int len3 = s3.length();
if (len1 + len2 != len3)return false;
//表示s1[0..i]和s2[0..j]能否组成s3[0..i+j]
dp[0][0] = true;
//初始化
for (int i = 1; i <= len1; i++)
{
dp[i][0] = dp[i - 1][0] &&s1[i - 1] == s3[i - 1];
}
for (int j = 1; j <= len2; j++)
{
dp[0][j] = dp[0][j - 1] && s2[j - 1] == s3[j - 1];
}
for (int i = 1; i <= len1; i++) {
for (int j = 1; j <= len2; 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[len1][len2];
}
int main() {
string s1;
string s2;
string s3;
cin >> s1;
cin >> s2;
cin >> s3;
bool judge=isInterleave(s1, s2, s3);
if (judge = true) {
cout << "YES" << endl;
}
else {
cout << "NO";
}
string result = "";
int y_count = 0;
int x_count = 0;
int x_length = s1.length();
int y_length = s2.length();
int x_now = 0;
int y_now = 0;
int x_next = 0;
int y_next = 0;
int x_pre = 0;
int y_pre = 0;
x_now = x_length;
y_now = y_length;
bool statue = 0;//0默认为左边走
if (dp[x_now][y_now] == 1)
{
while (1)
{
if (x_now == 0 && y_now == 0) {
break;
}
if (statue == 0)//默认往左边走
{
if (dp[x_now ][y_now-1] == 1)
{
result = "_" + result;
y_now = y_now - 1;//更新位置
y_count++;
}
else if (dp[x_now ][y_now-1] == 0)
{
statue = 1;//切换方向
result = s1[x_length - x_count - 1] + result;
x_now--;
x_count++;
}
}
else if (statue == 1)
{
if (dp[x_now - 1][y_now] == 1 && dp[x_now][y_now - 1] == 1)
{
//也要切换状态
statue == 0;//切换状态
result = "_" + result;
y_now--;
y_count++;
}
else if (dp[x_now-1][y_now ] == 1)
{
result = s1[x_length - x_count - 1] + result;
x_now--;
x_count++;
}
else if (dp[x_now-1][y_now] == 0) {
statue == 0;//切换状态
result = "_" + result;
y_now--;
y_count++;
}
}
}
}
cout << result << endl;
return 0;
}