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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值