28. Find the Index of the First Occurrence in a String
2026/1/12大约 1 分钟约 300 字
28. Find the Index of the First Occurrence in a String
难度: Easy
题目描述
Given two strings needle and haystack, return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Example 1:
Input: haystack = "sadbutsad", needle = "sad" Output: 0 Explanation: "sad" occurs at index 0 and 6. The first occurrence is at index 0, so we return 0.
Example 2:
Input: haystack = "leetcode", needle = "leeto" Output: -1 Explanation: "leeto" did not occur in "leetcode", so we return -1.
Constraints:
1 <= haystack.length, needle.length <= 104haystackandneedleconsist of only lowercase English characters.
解题思路
代码实现
解决方案
java
func strStr(haystack string, needle string) int {
if len(needle) > len(haystack) {
return -1
}
if len(needle) == len(haystack) && needle != haystack {
return -1
}
pi := make([]int,len(needle))
for i,j:=1,0;i<len(needle);i++{
for j>0 &&needle[i]!=needle[j]{
j=pi[j-1]
}
if needle[i]==needle[j]{
j++
}
pi[i] = j
}
for i,j:=0,0;i<len(haystack);i++{
for j>0&&haystack[i]!=needle[j]{
j=pi[j-1]
}
if(haystack[i]==needle[j]){
j++
}
if(j==len(needle)){
return i-len(needle)+1
}
}
return -1
}