leetcode028:Implement strStr()

問題描述

Implement strStr().


Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.


Update (2014-11-02):
The signature of the function had been updated to return the index instead of the pointer. If you still see your function signature returns a char * or String, please click the reload button  to reset your code definition.

分析

查找字符串needle在haystack第一次出現的位置索引。這裏需要用到已匹配部分的歷史信息,從而減少字符比較次數。舉例:haystack:abcdabXXX,needle:abcdabXXX,這裏我們可以利用的歷史信息即爲ab,這樣下次開始比較時從ab開始匹配。



代碼

這裏m用來記錄失敗匹配時已匹配部分有多少無需再比較的部分的字符數,上述例子m=2.

//運行時間:8ms
class Solution {
public:
	int strStr(string haystack, string needle) {
		if (needle.empty()) return 0;
		int h_len = haystack.length();
		int n_len = needle.length();
		if (h_len < n_len) return -1;
		//int ans = haystack.find(needle, 0);
		//if (ans == string::npos) return -1;
		//return ans;
		int i = 0;
		int m = 0;
		int j = 0;
		bool flag = false;
		int ans;
		while (i < h_len){
			ans = i - m;
			j = m;
			m = 0;
			while (i < h_len&&j < n_len&&haystack[i] == needle[j]){
				if (j){
					if (needle[j] == needle[m])
						m++;
					else m = 0;
				}
				i++; j++;
			}
			if (j == n_len) { flag = true; break; }
			if (!j) i++;
		}
		if (flag) return ans;
		return -1;
	}
};


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