LeetCode 0028. Find the Index of the First Occurrence in a String Solution Java | Python | C/C++ | JavaScripts | Go | Rust | Explaination + CODE

CoderIndeed
0
0028. Find the Index of the First Occurrence in a String

Description

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 <= 104
  • haystack and needle consist of only lowercase English characters.

Solutions

Solution 1: Traversal

We compare the string needle with each character of the string haystack as the starting point. If we find a matching index, we return it directly.

Assuming the length of the string haystack is n and the length of the string needle is m, the time complexity is O((n-m) × m), and the space complexity is O(1).

PythonJavaC++GoTypeScriptRustJavaScriptC#PHP
class Solution: def strStr(self, haystack: str, needle: str) -> int: n, m = len(haystack), len(needle) for i in range(n - m + 1): if haystack[i : i + m] == needle: return i return -1(code-box)

Solution 2: Rabin-Karp String Matching Algorithm

The Rabin-Karp algorithm essentially uses a sliding window combined with a hash function to compare the hashes of fixed-length strings, which can reduce the time complexity of comparing whether two strings are the same to O(1).

Assuming the length of the string haystack is n and the length of the string needle is m, the time complexity is O(n+m), and the space complexity is O(1).

GoTypeScript
func strStr(haystack string, needle string) int { n, m := len(haystack), len(needle) sha, target, left, right, mod := 0, 0, 0, 0, 1<<31-1 multi := 1 for i := 0; i < m; i++ { target = (target*256%mod + int(needle[i])) % mod } for i := 1; i < m; i++ { multi = multi * 256 % mod } for ; right < n; right++ { sha = (sha*256%mod + int(haystack[right])) % mod if right-left+1 < m { continue } // 此时 left~right 的长度已经为 needle 的长度 m 了,只需要比对 sha 值与 target 是否一致即可 // 为避免 hash 冲突,还需要确保 haystack[left:right+1] 与 needle 相同 if sha == target && haystack[left:right+1] == needle { return left } // 未匹配成功,left 右移一位 sha = (sha - (int(haystack[left])*multi)%mod + mod) % mod left++ } return -1 }(code-box)

Solution 3: KMP String Matching Algorithm

Assuming the length of the string haystack is n and the length of the string needle is m, the time complexity is O(n+m), and the space complexity is O(m).

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Check Now
Accept !