现在的位置: 首页 > 综合 > 正文

POJ1035 字符串处理(水)

2017年10月16日 ⁄ 综合 ⁄ 共 1735字 ⁄ 字号 评论关闭

嗯虽然题目上写着水,但是说起来都是辛酸泪啊T^T

题目概述:

如今你身为一个项目组的一员,给你输入一个字典,单词不超过10000个,以#标记结束。之后再给定几个单词,进行字符串的匹配。当然这个匹配不是完全匹配。如果字典里面的单词通过删除/加入/替换其中一个字母,就可以达到所给单词的话,也算匹配。输出所有匹配的可能字符串。

算法思想:

嗯说说为什么会辛酸泪吧。

开始的时候吓了一跳觉得枚举情况太多,后来突然想明白,其实根本不用枚举出正确的替换方式,拿删除举例,只要满足字典里单词的长度比所给字符串长度大1,且从前到后顺序遍历的时候只有一个差异就好了。

明白了这个之后我就开始实现这个想法,但是发现有一些问题,原因出在我用for编写循环,这样变量的跳动不受我的控制。继而我又强行分情况讨论,写了十分长的代码来实现这个正确的逻辑循环。最终成功了,但是因为直接用了string类导致TLE。

好的吧Orz,痛改前非使用char*,这回没问题了,利用strcmp判断字符串是否相等,利用strlen得到字符串的长度。

可是竟然900+ms是怎么回事.........

然后把判断删除/加入/替换的逻辑改用了网上人的逻辑,600+ms,还是不满意,把每个string的length只算一次,到了500多ms。

为什么别人同样的方法能够100+ms呢真是无语。

代码部分:

#include <iostream>
#include <string>
#include <string.h>
#include <vector>
using namespace std;
char myvector[10005][16];
char word[55][16];
int size;

bool ins_search(char* s1, char* s2) {
	int dif = 0;
	while (*s1) {
		if (*s1 != *s2) {
			s1++;
			dif++;
			if (dif > 1) return false;
		}
		else {
			s1++;
			s2++;
		}
	}
	return true;
}

bool rep_search(char* s1, char* s2) {
	int dif = 0;
	while (*s1) {
		if (*(s1++) != *(s2++)) {
			dif++;
			if (dif > 1) return false;
		}
	}
	return true;
}


bool del_search(char* s1, char* s2) {
	int dif = 0;
	while (*s2) {
		if (*s1 != *s2) {
			s2++;
			dif++;
			if (dif > 1) return false;
		}
		else {
			s1++; s2++;
		}
	}
	return true;
}

int main() {
	int size = 0; int j = 0;
	while (cin >> myvector[size]) {
		if (myvector[size][0] == '#') break;
		size++;
	}
	while (cin >> word[j]) {
		if (word[j][0] == '#') break;
		int word_length = strlen(word[j]);
		bool find = false;
		for (int i = 0; i < size; i++) {
			if (!strcmp(myvector[i],word[j])) {
				cout << word[j] << " is correct" << endl;
				find = true;
				break;
			}
		}

		if (find) continue;

		cout << word[j] << ":";
		for (int i = 0; i < size; i++) {
			int length = strlen(myvector[i]);
			if (word_length + 1 == length) {
				if (del_search(word[j], myvector[i])) {
					cout << " " << myvector[i];
				}
			}
			if (word_length == length) {
				if (rep_search(word[j], myvector[i])) {
					cout << " " << myvector[i];
				}
			}
			if (word_length - 1 == length) {
				if (ins_search(word[j], myvector[i])) {
					cout << " " << myvector[i];
				}
			}
		}
		cout << endl;
		j++;
	}
	return 0;
}

抱歉!评论已关闭.