初級算法之字符串:實現 strStr()

實現 strStr() 函數。

給定一個 haystack 字符串和一個 needle 字符串,在 haystack 字符串中找出 needle 字符串出現的第一個位置 (從0開始)。如果不存在,則返回 -1。

示例 1:

輸入: haystack = “hello”, needle = “ll” 輸出: 2

示例 2:

輸入: haystack = “aaaaa”, needle = “bba” 輸出: -1

說明:

當 needle 是空字符串時,我們應當返回什麼值呢?這是一個在面試中很好的問題。

對於本題而言,當 needle 是空字符串時我們應當返回 0 。這與C語言的 strstr() 以及 Java的 indexOf()
定義相符。

這道題的最佳解法還是KMP。首先分析一下KMP的原理
(1)尋找前後綴的算法 時間空間
複雜度O(n)
如abcdabca
首先設置i=0 j=1
if(i==0 && s[i]!=s[j]) next[j++]=0;
else if(s[i]==s[j]){
next[j++] = i+1;
i++;
}
else if(s[i]!=s[j]){
i = next[i-1];
}

(2)利用next數組完成匹配
設置兩個指針ij分別指向主串和子串,若相同則i++ j++
否則就讓j=next[j-1]

貼代碼:

void createNext(vector<int> &next, string s) {
	int i = 0, j = 1;
	while (j<s.size()) {
		if (i == 0 && s[i] != s[j]) next[j++] = 0;
		else if (s[i] == s[j]) {
			next[j++] = i + 1;
			i++;
		}
		else if (s[i] != s[j]) i = next[i - 1];
	}
}

int strStr(string haystack, string needle) {
	if (needle.size() == 0) return 0;
	vector<int> next(needle.size());
	createNext(next, needle);
	int i = 0, j = 0;
	while (i < haystack.size() && j < needle.size()) {
		if (haystack[i] == needle[j]) {
			i++;
			j++;
		}
		else {
			if (j == 0) i++;
			else j = next[j - 1];
		}
	}
	if (j != needle.size()) return -1;
	return i - needle.size();
}
發佈了44 篇原創文章 · 獲贊 0 · 訪問量 1295
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章