[noj 1521] +-字符串

来源:互联网 发布:stm32官方烧录软件 编辑:程序博客网 时间:2024/05/17 01:37

题目链接:http://acm.nbut.cn/Problem/view.xhtml?id=????(OJ打不开了 = =、)

这道题让你通过交换两个相邻的数,如果交换后上下两个字符串相等,则输出最小交换次数,否则输出-1.

那么我们从最后一个数开始查找,如果相等,往前移一位,在判断是否相等,反复多次找到相等的后使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;
}

黑赵晓,我们特专业!

0 0
原创粉丝点击