Leetcode28
链接:力扣 。
题目:
实现 strStr() 函数。
给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。
示例1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
思路:
题目的意思就是考察KMP。(总不可能在面试的时候给面试官来个暴力循环或者调库函数吧...)。
KMP详解看链接:代码随想录 。
参考代码:
class Solution {
public:
void get_next(int *next, string s) {
next[0] = -1;
int j = -1;
for (int i = 1; i < s.size(); i++) {
while (s[i] != s[j + 1] && j != -1) {
j = next[j];
}
if (s[i] == s[j + 1]) {
j++;
}
next[i] = j;
}
}
int strStr(string haystack, string needle) {
if (needle.size() == 0) {
return 0;
}
int next[needle.size()];
get_next(next, needle);
int j = -1;
for (int i = 0; i < haystack.size(); i++) {
while (haystack[i] != needle[j + 1] && j != -1) {
j = next[j];
}
if (haystack[i] == needle[j + 1]) {
j++;
}
if (j == needle.size() - 1) {
return (i - j);
}
}
return -1;
}
};