POJ1035 字符串處理(水)

嗯雖然題目上寫着水,但是說起來都是辛酸淚啊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;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章