SRM 597 1A 2013.12.6
DIV 1
250
题目大意:两个长度相同的字符串A和B,对A进行操作:从A中任意挑选一个字符,放在A的最开始,问最少经过多少次,可以变成B。
解题思路:从B的最后一个字符开始,从后往前,看A能匹配的B的最长的连续的子串。用长度减去子串长度即可。
错误原因:刚开始用了最长公共子序列,WA掉了最后一组数,突然想到其实就是选一个字符往前移动,那么只要看A能满足的最长的B的最末端的连续子串就行啦!就是在想应该怎么样一种匹配方式,原来是这种。
Problem Statement
Little Elephant from the Zoo of Lviv likesstrings.
You are given a string A and a string B ofthe same length. In one turn Little Elephant can choose any character of A andmove it to the beginning of the string (i.e., before the first character of A).Return the minimal number of turns needed to transform A into B. If it'simpossible, return -1 instead.
Definition
Class:
LittleElephantAndString
Method:
getNumber
Parameters:
string, string
Returns:
int
Method signature:
int getNumber(string A, string B)
(be sure your method is public)
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)
"ABC"
"CBA"
Returns: 2
The optimal solution is to make two turns.On the first turn, choose character 'B' and obtain string "BAC". Onthe second turn, choose character 'C' and obtain "CBA".
1)
"A"
"B"
Returns: -1
In this case, it's impossible to transformA into B.
2)
"AAABBB"
"BBBAAA"
Returns: 3
3)
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"ZYXWVUTSRQPONMLKJIHGFEDCBA"
Returns: 25
4)
"A"
"A"
Returns: 0
5)
"DCABA"
"DACBA"
Returns: 2
This problem statement is the exclusive andproprietary property of TopCoder, Inc. Any unauthorized use or reproduction ofthis information without the prior written consent of TopCoder, Inc. isstrictly prohibited. (c)2003, TopCoder, Inc. All rights reserved.
112.89
#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
class LittleElephantAndString
{
private:int max(int a,int b)
{
if(a>b) return a;else return b;
}
public:int getNumber(string A, string B)
{
int chA[30]={0},chB[30]={0};
int i,j,len=A.size();
int ans=0;
for(i=0;i<len;i++)
{
chA[A[i]-'A']++;
chB[B[i]-'A']++;
}
for(j=0;j<26;j++)
if (chA[j]!=chB[j]) return -1;
int p=len-1;
for(i=len-1;i>=0;i--)
{
if(A[i]==B[p])
{
ans++;
p--;
}
}
return len-ans;
}
};