Problem Statement | |||||||||||||
| Little Elephant from the Zoo of Lviv likes strings. You are given a string A and a string B of the same length. In one turn Little Elephant can choose any character ofA and move it to the beginning of the string (i.e., before the first character ofA). Return the minimal number of turns needed to transform A into B. If it's impossible, return -1 instead. | ||||||||||||
Definition | |||||||||||||
|
| ||||||||||||
| |||||||||||||
| |||||||||||||
Constraints | |||||||||||||
- | A will contain between 1 and 50 characters, inclusive. | ||||||||||||
- | B will contain between 1 and 50 characters, inclusive. | ||||||||||||
- | A and B will be of the same length. | ||||||||||||
- | A and B will consist of uppercase letters ('A'-'Z') only. | ||||||||||||
Examples | |||||||||||||
0) |
| ||||||||||||
|
| ||||||||||||
1) |
| ||||||||||||
|
| ||||||||||||
2) |
| ||||||||||||
|
| ||||||||||||
3) |
| ||||||||||||
|
| ||||||||||||
4) |
| ||||||||||||
|
| ||||||||||||
5) |
| ||||||||||||
|
|
类型:字符串 难度:2.5
题意:给出A,B两个字符串,长度相同,允许对A做一种操作:将A中任意位置字符放到第一个位置,问对A做几次这个操作,A和B相同,若不可能,返回-1。
分析:最长公共子序列的变形问题,dp解决即可。即从A的尾部反向遍历,dp[i]表示从A末尾到第i个位置 与 B从末尾开始匹配的最大长度,A匹配字符可以不连续,B匹配字符位置连续,且必须从末尾开始匹配,即A[m]=B[n],i<m<len(A),n=j,j+1,...,len(B)。
递推方程:dp[i] = max(dp[j]+1),i<j<len(A),A[i]==B[len(B)-dp[j]-1]
答案就是len(A)减去最大匹配长度。
代码:
#include<string>
#include<cstdio>
#include<vector>
#include<cstring>
#include<map>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<set>
using namespace std;
class LittleElephantAndString
{
public:
int getNumber(string A, string B)
{
int la = A.length();
int cnt[30];
memset(cnt,0,sizeof(cnt));
for(int i=0; i<la; i++)
{
cnt[A[i]-'A']++;
cnt[B[i]-'A']--;
}
for(int i=0; i<26; i++)
if(cnt[i]!=0) return -1;
int dp[60],ans = 0;
memset(dp,0,sizeof(dp));
if(A[la-1] == B[la-1])
{
dp[la-1] = 1;
ans = 1;
}
else dp[la-1] = 0;
for(int i=la-2; i>=0; i--)
{
for(int j=la-1; j>i; j--)
{
int tmp;
if(A[i] == B[la-dp[j]-1])
tmp = dp[j]+1;
else
tmp = 0;
if(tmp > dp[i]) dp[i] = tmp;
if(tmp > ans) ans = tmp;
}
}
return la-ans;
}
};