leetcode 28. Implement strStr()

本文介绍了两种常见的字符串匹配算法:暴力解法和KMP算法。通过具体实现,展示了如何寻找一个字符串(needle)在另一个字符串(haystack)中的起始位置。适用于初学者了解基本的字符串匹配原理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.题目

Implement strStr().

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

给你两个字符串haystack和needle,如果needle是haystack的子串,返回needle在haystack的起始位置,否则返回-1。

2.思路 

这道题考察的是字符串匹配的算法。

解法一:暴力解法。

class Solution {
public:
    int strStr(string haystack, string needle) {
    int a = haystack.size();
    int b = needle.size();
    if (b == 0) return 0;

    int j;
    for (int i = 0; i < a-b+1; i++) {
        for (j = 0; j < b && haystack[i+j] == needle[j]; j++);
        if (j == b) return i;
    }

    return -1;
    }
};
解法二:KMP算法。

关于字符串匹配其他博客上有很详细的讲解,这里我先放上链接。http://www.cnblogs.com/c-cloud/p/3224788.html(个人感觉说的比较详细)

class Solution {
public:
	// next数组的作用:当T失配时,next数组对应的元素知道应该用T串的哪个元素进行下一轮的匹配
	vector<int> getNext(string T) { 
		int len = T.size();
		vector<int> next(len);
		int i = 0, j = -1; //i代表T的后缀,j代表T的前缀,其实是为了找出前后缀的最长公共长度
		next[0] = -1;
		while (i < len-1) {
			if (-1 == j || T[i] == T[j]) {
				i++; j++;
				if (T[i] == T[j])
					next[i] = next[j];
				else
					next[i] = j;
			}
			else
				j = next[j];
		}
		return next;
	}
	int kmp(string S, string T) {
		int len1 = S.size(); // 注意此处不能用size_t声明,理由见@1
		int len2 = T.size();
		if (len2 == 0) return 0;
		vector<int> next(len2);
		next = getNext(T);
		int i = 0, j = 0;
		while (i < len1 && j < len2) {
			if (S[i] == T[j] || -1 == j ) { // 为什么此处j会等于-1呢?因为j可能为0,当s[0]!=T[0]时,j=next[0]=-1
				i++; j++;
			}
			else
				j = next[j];
			if (j >= len2) return i - j; // @1 : 如果len2是用size_t声明的话,int j 总是大于 len2的
		}
		return -1;
	}
	int strStr(string haystack, string needle) {
		return kmp(haystack, needle);
	}
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值