题目链接:http://acm.nbut.cn/Problem/view.xhtml?id=????(OJ打不开了 = =、)
那么我们从最后一个数开始查找,如果相等,往前移一位,在判断是否相等,反复多次找到相等的后使count+=j-t;count表示交换次数,j表示下面的字符串j位置的字符,t表示上面字符串t位置的字符。
代码如下:
#include<stdio.h>
#include<string.h>
char s1[5005];
char s2[5005];
int main()
{
while(~scanf("%s",s1))
{
int count = 0;
scanf("%s",s2);
int len1 = strlen(s1);
int len2 = strlen(s2);
int len = len1;
for(int i = len-1,j = len - 1;i>=0;i--,j--)
{
if(s1[i]==s2[j])
{
continue;
}
else
{
int t = i;
while(t--)
{
if(s1[t]==s2[j])
{
int temp = s1[t];
s1[t] = s1[j];
s1[j] = temp;
count+=j-t;
break;
}
}
}
}
if(strcmp(s1,s2)==0)
printf("%d\n",count);
else
printf("-1\n");
}
return 0;
}
黑赵晓,我们特专业!