Implement strStr() 实现strStr()

本文介绍了如何实现strStr()函数,通过两种方法来查找一个字符串在另一个字符串中的首次出现位置。第一种方法使用双层循环进行暴力匹配,第二种方法则应用了KMP算法,提高了查找效率。

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

实现 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() 定义相符。

思路一:直接采用两层循环的暴力法来做,逐个比较每个字符haystack[i]和needle[0],如果对应字符有任何一个不相等,就跳过,继续比较haystack[i+1],如果对应字符相等就继续比较haystack[i+1]和needle[1],一直比较到needle的最后节点,如果needle[j]中的j等于needle的长度,说明找到了一个答案,直接返回i。如果外层遍历完还没有找到答案就返回-1。

参考代码:

class Solution {
public:
    int strStr(string haystack, string needle) {
	if (needle.empty()) return 0;
	int m = haystack.size();
	int n = needle.size();
	if (n > m) return -1;
	for (int i = 0; i <= m - n; i++) {
		int j = 0;
		for (; j < n; j++) {
			if (haystack[i + j] != needle[j]) break;
		}
		if (j == n) return i;
	}
	return -1;        
    }
};

思路二:这里先粘贴上两篇介绍kmp算法的博客。

kmp链接kmp链接2

具体原理不解释了,比较复杂,这里直接给出实现代码:

class Solution {
public:
void makeNext(char *ptr, int *next,int len) {
	int k;
	next[0] = 0;
	for (int i = 1, k = 0; i < len; i++) {
		while (k > 0 && ptr[k] != ptr[i]) {
			k = next[k - 1];
		}
		if (ptr[k] == ptr[i]) {
			k++;
		}
		next[i] = k;
	}
}
int kmp(char *str, int lenStr, char *ptr, int lenPtr) {
	int k;
	int *next = new int[lenPtr];
	makeNext(ptr, next,lenPtr);
	for (int i = 0,k=0; i < lenStr; i++) {
		while (k > 0 && str[i] != ptr[k]) {
			k = next[k - 1];
		}
		if (str[i] == ptr[k]) {
			k++;
		}
		if (k == lenPtr) {
			delete[] next;
			return i - lenPtr + 1;
		}
	}
	delete[] next;
	return -1;
}
int strStr(string haystack, string needle) {
	if (needle.empty()) return 0;
	int lenStr = haystack.size();
	int lenPtr = needle.size();
	return kmp((char *)haystack.c_str(), haystack.size(), (char *)needle.c_str(), needle.size());
}
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值