NYOJ915 +-字符串

原题链接

主要思路:从左到右,逐个比较,若有不同,标记此不同地点,并向右搜寻首个相同点,从该点开始挨个与左边位置交换并统计交换次数。

#include <stdio.h>
#include <string.h>
#define MAX 5000 + 2
char str[MAX], str2[MAX];

int find(int i){
	int j = i, count = 0;
	char t;
	while(str[j] != str2[i])
		++j;
	while(j > i){
		t = str[j];
		str[j] = str[j - 1];
		str[j - 1] = t;
		--j;
		++count;
	}
	return count;
}

int main(){
	int count;
	while(scanf("%s%s", str, str2) == 2){
		int a = 0, b = 0;
		for(int i = 0; str[i] != '\0'; ++i)
			if(str[i] == '-') ++a;
		for(int i = 0; str2[i] != '\0'; ++i)
			if(str2[i] == '-') ++b;
		if(a != b){
			printf("-1\n");
			continue;
		}
		count = 0;
		for(int i = 0; str2[i] != '\0'; ++i){
			if(str[i] != str2[i])
				count += find(i);
		}
		printf("%d\n", count);
	}
	return 0;
}

优化后的代码:思路有所改变。不再模拟整个过程,时间大幅缩短。


#include <stdio.h>
#include <string.h>
#define MAX 5000 + 2
char str[MAX], str2[MAX];

int main(){
	int count, ok, i, j;
	while(scanf("%s%s", str, str2) == 2){
		count = 0;
		for(i = 0, ok = 1; str2[i] != '\0'; ++i){			
			if(str[i] != str2[i]){
				for(j = i + 1, ok = 0; str[j] != '\0'; ++j)
					if(str[j] == str2[i]){
						count += j - i;
						str[j] = str[i];
						ok = 1;
						break;
					}				
			}
			if(!ok){
				printf("-1\n");
				break;
			}
		}
		if(ok) printf("%d\n", count);
	}
	return 0;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值