PAT (Top Level) Practice 1015 Letter-moving Game (35 分

Letter-moving Game

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

这个题其实就是求S和T的最长公共子序列,但是要求这个子序列是T中的子串,也就是在T中是连续的,可以用暴搜也可以用dp,时间复杂度差不多.

下面是用暴搜AC的代码,时间复杂度是O( n 2 n^2 n2)

#include <iostream>
#include <string>
#include <cmath>
int ans;
using namespace std;

int main()
{
    string a,b;
    cin>>a>>b;
    int cnt;
    for(int i = 0; i<b.size(); i++) {
        cnt = 0;
        int k = i;
        for (int j = 0; j<a.size(); j++) {
            if(b[k]==a[j]) {
                k++;
                cnt++;
            }
        }
        ans = max(cnt,ans);
    }
    cout<<a.length()-ans;
    return 0;
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值