题目链接:
Description
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: tcraeteAs 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: catrteeFinally, notice that it is impossible to form "cttaree" from "cat" and "tree".
Input
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.
Output
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.
Sample Input
3
cat tree tcraete cat tree catrtee cat tree cttareeSample Output
Data set 1: yes
Data set 2: yes Data set 3: no题意
给定3个字符串,问在不改变前两个字符串内字母的相对位置的前提下能否组成第3个字符串,保证前两个字符串长度之和等于第三个字符串。
题解:
这道题的解法有多种,有说用DP的,有说用最短路的、、、无奈我只会DFS,最后用DFS跑出来的这道题,而且思路也比较简单。
设置一个标记,表示匹配到了第3个字符串的第几个字母,在DFS时,只要有一个字母被跳过了,那就说明肯定无解,因为:保证前两个字符串长度之和等于第三个字符串,在输入时加了一个对字母组成的剪枝,刚开始超时就卡在这个判断上了。代码
#define _CRT_SECURE_NO_WARNINGS#include#include #include