67,633
社区成员
发帖
与我相关
我的任务
分享实现 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
方法一:暴搜
让字符串needle 与 字符串 haystack 中所有长度为m的字符串均匹配一次。
时间复杂度: O(n* m),最坏的情况要将两个字符串里存在的数组都匹配一次;
空间复杂读:O(1)
C++:
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.size(), m = needle.size() ;
for (int i = 0 ; i + m <= n ; i++) {
bool flag = true ;
for (int j = 0; j <m; j++) {
if (haystack[i+j] != needle[j]) {
flag = false ;
break;
}
}
if (flag) return i ;
}
return -1 ;
}
};
Golang:
func strStr(haystack string, needle string) int {
n, m := len(haystack), len(needle)
outer:
for i:= 0 ; i +m <= n; i++ {
for j := range needle {
if haystack[i+j] != needle[j] {
continue outer
}
}
return i
}
return -1
}
方法二:KMP算法
分享优质KMP讲解:
https://www.cnblogs.com/zzuuoo666/p/9028287.html
主要思想:
本题可以作为KMP算法模板题
时间复杂度: O(n+ m),至多将两个字符串都遍历一次 ;
空间复杂度: O(1) ;
C++:
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) return 0 ;
int n = haystack.size(), m = needle.size() ;
haystack = ' '+haystack, needle = ' '+ needle ;
//求needle串的next数组
vector<int> next(m+1) ;
for (int i =2, j = 0; i<= m; i++) {
while(j && needle[i]!= needle[j+1]) j = next[j] ;
if (needle[i] == needle[j+1]) j++ ;
next[i] = j ;
}
//字符串的匹配
for (int i =1, j = 0 ; i<= n; i++) {
while ( j && haystack[i]!= needle[j+1]) j = next[j] ;
if (haystack[i] == needle[j+1]) j++ ;
if (j == m) return i - m ; // 从0开始是 i - m-1 从1开始是 i - m
// return j = next[j] 再次匹配的值
}
return -1 ;
}
};
Golang:
func strStr(haystack string, needle string) int {
n, m := len(haystack), len(needle)
if m == 0 {
return 0
}
haystack = " " + haystack
needle = " " + needle
next := make([]int, m+1)
for i:= range next {
next[i] = 0
}
j:= 0
for i:=2; i <= m; i++ {
for j!= 0 && needle[i] != needle[j+1] {
j = next[j]
}
if needle[i] == needle[j+1] {
j++
}
next[i] = j
}
k:= 0
for i := 1; i<= n; i++ {
for k !=0 && haystack[i] != needle[k+1] {
k = next[k]
}
if haystack[i] == needle[k+1] {
k++
}
if k == m {
return i - m
}
}
return -1
}