首页 > 其他 > 详细

NYOJ915 +-字符串

时间:2014-03-14 00:20:10      阅读:521      评论:0      收藏:0      [点我收藏+]

原题链接

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

#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;
}


NYOJ915 +-字符串,布布扣,bubuko.com

NYOJ915 +-字符串

原文:http://blog.csdn.net/chang_mu/article/details/21188171

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!