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.
用 Rabin-Karp 算法
impl Solution {
pub fn str_str(haystack: String, needle: String) -> i32 {
let needle_hash = needle.chars().

该博客介绍了如何运用Rabin-Karp算法来解决LeetCode中的字符串首次出现位置查找问题。通过两个示例展示了算法的应用,包括在输入字符串`sadbutsad`中找到`sad`的索引0,以及在`leetcode`中未找到`leeto`的返回值-1。文章强调了算法在处理英文小写字母组成的字符串时的约束条件。
最低0.47元/天 解锁文章
2395

被折叠的 条评论
为什么被折叠?



