28. 实现 strStr()
题目描述:
实现 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
示例 3:
输入:haystack = "", needle = ""
输出:0
提示:
- 0 <= haystack.length, needle.length <= 5 * 1 0 4 10^4 104
haystack
和needle
仅由小写英文字符组成
JAVA代码:
基本方法:
最简单,直接运用string方法中的indexOf()方法,获取needle在haystack中的位置。
了解就行,不可取巧,继续思考实现方法。
class Solution {
public int strStr(String haystack, String needle) {
return haystack.indexOf(needle);
}
}
暴力解法:
字符串匹配算法:haystack为主串,needle为模式串。
(类似扫描仪一样,从haystack某个位置开始扫描,是否和needle相同,不同则下一个位置继续扫描)
视频讲解会更清晰,可以参考:
视频讲解: https://leetcode-cn.com/problems/implement-strstr/solution/zhe-ke-neng-shi-quan-wang-zui-xi-de-kmp-8zl57/
class Solution {
public int strStr(String haystack, String needle) {
int hlen = haystack.length();
int nlen = needle.length();
for(int i = 0;i+nlen<=hlen;i++){
boolean flag = true;
for(int j = 0;j<nlen;j++){
//haystack指定位置与needle挨个进行匹配
//若有一个不相同,就置信号为false
if(haystack.charAt(i+j)!=needle.charAt(j)){
flag = false;
break;
}
}
//信号为true说明这个位置是第一个匹配的位置。
if(flag==true){
return i;
}
}
return -1;
}
}
KMP算法:
class Solution {
public int strStr(String haystack, String needle) {
//字符串转为字符数组
char[] t = haystack.toCharArray();
char[] p = needle.toCharArray();
//判空
if(p.length==0){
return 0;
}
//建立next数组
int[] next = new int[p.length];
//要和next[0]相同
int j = -1;
int i = 0;
//设置初值为-1
next[0] = -1;
while(i<p.length-1){
if(j==-1||p[i]==p[j]){
i++;
j++;
next[i] = j;
}else{
j = next[j];
}
}
//KMP算法主体
int k = 0;
int l = 0;
while(k<t.length&&l<p.length){
if(l==-1||t[k]==p[l]){
k++;
l++;
}else{
l=next[l];
}
}
//如果长度相等,说明匹配成功
if(l==p.length){
return k-p.length;
}else{
return -1;
}
}
}
KMP优化:
class Solution {
public int strStr(String haystack, String needle) {
//字符串转为字符数组
char[] t = haystack.toCharArray();
char[] p = needle.toCharArray();
//判空
if(p.length==0){
return 0;
}
//建立nextval数组
int[] nextval = new int[p.length];
//要和nextval[0]相同
int j = -1;
int i = 0;
//设置初值为-1
nextval[0] = -1;
while(i<p.length-1){
if(j==-1||p[i]==p[j]){
i++;
j++;
if(p[i]!=p[j]){
nextval[i] = j;
}else{
nextval[i] = nextval[j];
}
}else{
j = nextval[j];
}
}
//KMP算法主体
int k = 0;
int l = 0;
while(k<t.length&&l<p.length){
if(l==-1||t[k]==p[l]){
k++;
l++;
}else{
l=nextval[l];
}
}
//如果长度相等,说明匹配成功
if(l==p.length){
return k-p.length;
}else{
return -1;
}
}
}
这部分在简单题中,有些超纲。
KMP算法对于大部分人来说还是很难理解的。
我通过书本+B站+leetcode的实现的逐步学习,终于把KMP算法大概弄明白了。
感兴趣的可以参考我的另一篇博文,专门讲解了KMP算法的原理与代码实现:
https://blog.csdn.net/woailiqi12134/article/details/118228491