1015 Letter-moving Game (35)(35 分)
Here is a simple intersting letter-moving game. The game starts with 2 strings S and T consist of lower case English letters. S and T contain the same letters but the orders might be different. In other words S can be obtained by shuffling letters in String T. At each step, you can move one arbitrary letter in S either to the beginning or to the end of it. How many steps at least to change S into T?
Input Specification:
Each input file contains one test case. For each case, the first line contains the string S, and the second line contains the string T. They consist of only the lower case English letters and S can be obtained by shuffling T’s letters. The length of S is no larger than 1000.
Output Specification:
For each case, print in a line the least number of steps to change S into T in the game.
Sample Input:
iononmrogdg
goodmorning
Sample Output:
8
Sample Solution:
(0) starts from iononmrogdg
(1) Move the last g to the beginning: giononmrogd
(2) Move m to the end: giononrogdm
(3) Move the first o to the end: ginonrogdmo
(4) Move r to the end: ginonogdmor
(5) Move the first n to the end: gionogdmorn
(6) Move i to the end: gonogdmorni
(7) Move the first n to the end: googdmornin
(8) Move the second g to the end: goodmorning
题目出的非常的棒。
实际上是求 s中的子序列和t中的子串相等的这个串 它的的最大长度
但是题目表述成这种模式一下子就不太能想的到。
正确性显而易见。
就是S-》P,当然是S中某个序列和P中某个子串相等,那么我只要按照特定顺序
把S中非这个序列的元素向前向后做一次操作就可以了。
具体做法就是两个指针——two pointer
我代码写的蛮清晰的,应该很好理解。
#include <bits/stdc++.h>
using namespace std;
char s[10005], t[10005];
int main(void)
{
scanf("%s%s", s+1, t+1);
int len = strlen(s+1);
int i, j;
int start;
int res = 0;
for (start = 1; start <= len; start++)
{
j = start, i = 1;
while (i <= len && j <= len)
{
if (s[i] == t[j])
{
i++, j++;
}
else
{
i++;
}
}
res = max(res, j - start);
}
cout << len - res;
}
如果是求最长公共序列就是DP,最长公共子串就是KMP
这种一个是序列,一个是串的还真没碰到过hhhhh