013:Zipper
总时间限制: 1000ms 内存限制: 65536kB
描述
Given three strings, you are to determine whether the third string can be formed by combining the characters in the first two strings. The first two strings can be mixed arbitrarily, but each must stay in its original order.
For example, consider forming “tcraete” from “cat” and “tree”:
String A: cat
String B: tree
String C: tcraete
As you can see, we can form the third string by alternating characters from the two strings. As a second example, consider forming “catrtee” from “cat” and “tree”:
String A: cat
String B: tree
String C: catrtee
Finally, notice that it is impossible to form “cttaree” from “cat” and “tree”.
输入
The first line of input contains a single positive integer from 1 through 1000. It represents the number of data sets to follow. The processing for each data set is identical. The data sets appear on the following lines, one data set per line.
For each data set, the line of input consists of three strings, separated by a single space. All strings are composed of upper and lower case letters only. The length of the third string is always the sum of the lengths of the first two strings. The first two strings will have lengths between 1 and 200 characters, inclusive.
输出
For each data set, print:
Data set n: yes
if the third string can be formed from the first two, or
Data set n: no
if it cannot. Of course n should be replaced by the data set number. See the sample output below for an example.
样例输入
3
cat tree tcraete
cat tree catrtee
cat tree cttaree
样例输出
Data set 1: yes
Data set 2: yes
Data set 3: no
思想
本题由于要按顺序,而且两字符串长度之和恰好等于最后一个字符串,就要求任意字符串中第i个以前的i-1个字符一定参与了组成,否则无法完成组合,因此可以将状态设为dp[i][j]表示s1中前i个字符和s2中前j个字符可以构成d中前i+j个字符串,若要看dp[i][j]能否完成,则对s1要看dp[i-1][j]是否可以,且d[i+j-1]=s1[i-1];对s2要看dp[i][j-1]是否可以,且s2[j-1]=d[i+j-1];边界条件是酒dp[0][0]一定能组成为true,故依次扫描就录下结果最终的dp[len1][len2]就是结果。(注意下标代表的意义)
#include<iostream>
#include<vector>
#include<string>
using namespace std;
bool check(const string& s1, const string& s2, const string& d) {
int len1 = s1.length(), len2 = s2.length();
vector<vector<bool>> dp(len1 + 1, vector<bool>(len2 + 1, false));
//dp[i][j]表示s1中前i个字符和s2中前j个字符可以构成d中前i+j个字符串
dp[0][0] = true;//0个元素一定能构成
for (int i = 0; i <= len1; ++i)
for (int j = 0; j <= len2; ++j) {
if (i >= 1 && dp[i - 1][j] && d[i + j - 1] == s1[i - 1])
dp[i][j] = true;
if (j >= 1 && dp[i][j - 1] && d[i + j - 1] == s2[j - 1])
dp[i][j] = true;
}
return dp[len1][len2];
}
int main() {
int N = 0;
cin >> N;
int cnt = 1;
while (N--) {
string src1, src2, dst;
cin >> src1 >> src2 >> dst;
if (check(src1,src2,dst))
cout << "Data set " << cnt++ << ": yes" << endl;
else
cout << "Data set " << cnt++ << ": no" << endl;
}
return 0;
}
本文介绍了一种算法,用于判断第三个字符串是否能由前两个字符串的字符按原顺序组合而成。通过动态规划方法,设定状态dp[i][j]表示s1前i字符与s2前j字符能否构成d前i+j字符,实现对给定字符串的有效验证。
589

被折叠的 条评论
为什么被折叠?



