“实现strStr()。”
题目链接:
来源:力扣(LeetCode)
链接:28. 实现 strStr() - 力扣(LeetCode) (leetcode-cn.com)
实现 strStr() 函数。
给你两个字符串 haystack 和 needle ,请你在 haystack 字符串中找出 needle 字符串出现的第一个位置(下标从 0 开始)。如果不存在,则返回 -1 。
说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。
示例 1:
输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:
输入: haystack = "aaaaa", needle = "bba"
输出: -1
这个题是经典的字符串单模匹配的模型,可以使用字符串匹配算法解决,本文使用KMP(Knuth Morris Pratt)算法解这道题。
KMP算法的主要逻辑就是,计算next数组,通过循环来对比target与txt字符串。
代码参考:
public class Solution {
public int StrStr(string haystack, string needle) {
if(needle == "") return 0;
int[] next = GetNext(needle); //获取next数组
int i = 0, j = 0;
while(i < haystack.Length)
{
if(haystack[i] == needle[j])
{
i++;
j++;
}
else
{
if(i < haystack.Length)
{
if(j == 0) i++;
else j = next[j - 1]; //回溯,KMP之精髓,与next中的回溯同理
}
}
if(j == needle.Length) return i - j;
}
return -1;
}
public int[] GetNext(string str)
{
int[] next = new int[str.Length];
int i = 1, j = 0; //i不能等于1,否则无法错位相比
next[0] = 0;
while(i < str.Length)
{
if(str[i] == str[j])
{
j++;
next[i] = j;
i++;
}
else
{
if(j == 0)
{
next[i] = 0;
i++;
}
else
{
j = next[j - 1]; //回溯
}
}
}
return next;
}
}
时间复杂度 : O(n+m)
其中m是字符串needle的长度,m是字符串haystack的长度。
空间复杂度: O(m)
其中m是字符串needle的长度。
有时间可以详细了解一下KMP算法。