实现 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算法的博客。
具体原理不解释了,比较复杂,这里直接给出实现代码:
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());
}
};