交换字符,codeforces1015B

题意:

给两个字符串,s,t需要把他们变成一样的。对于字符串s,可以让它的两个相邻字符s[i],s[i+1]交换(1<=i<n)。不需要让操作次数最少,但是操作的次数不能超过1e4求一种方案。如果s和t永远无法相等就输出-1

输出操作次数以及每次发生交换的位置i.

题解:

对于t的每个字符,如果和s对应的位置的字符一样就不需要交换。如果不一样,就需要往后面查找,如果查找不到,就说明s,t不可能相同,输出-1;查找到了,就记录一个答案。并交换一次。

#pragma warning(disable:4996)
#include<algorithm>
#include<cmath>
#include<iostream>
#include<cstdio>
#include<cstring>
#include<stack>
#include<vector>
#include<map>
#include<string>
#include<set> 
#include<queue>
using namespace std;
typedef long long ll;
string s1, s2;//两个字符串
int ans[100005], cnt;
int main()
{
	int flag = 1, n, j, i = 0;
	cin >> n;
	cin >> s1 >> s2;
	while (i < n)
	{
		for (j = i; j < n; j++)
			if (s2[i] == s1[j])
			//从这个字符到结尾有没有相同的字符
				break;
		if (j < n)//找到了
		{
			if (i != j)//不在同一个位置,交换
			{
				ans[++cnt] = j;
				char t;
				t = s1[j];
				s1[j] = s1[j - 1];
				s1[j - 1] = t;
				if (s1[i] == s2[i])i++;
				//必须要一直交换到相同
			}
			else i++;
		}
		else//后面没有相同字符了
		{
			flag = 0;
			break;
		}
	}
	if (!flag)printf("-1\n");
	else
	{
		printf("%d\n", cnt);
		for (i = 1; i <= cnt; i++)
			printf("%d ", ans[i]);
		printf("\n");
	}
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值