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().fold(0, |mut h, c| {
            h *= 256;
            h += c as i32;
            h %= 101;
            h
        });
        let power = (1..needle.len()).fold(1, |mut p, _| {
            p *= 256;
            p %= 101;
            p
        });
        let mut haystack_hash = 0;
        let mut queue = Vec::new();
        for (i, c) in haystack.chars().enumerate() {
            if queue.len() == needle.len() {
                haystack_hash += 101;
                haystack_hash -= queue.remove(0) as i32 * power % 101;
            }
            haystack_hash *= 256;
            haystack_hash += c as i32;
            haystack_hash %= 101;
            queue.push(c);
            if queue.len() == needle.len() && needle_hash == haystack_hash && haystack[i + 1 - needle.len()..i + 1] == needle[..] {
                return (i + 1 - needle.len()) as i32;
            }
        }
        -1
    }
}


版权声明:本文为wangjun861205原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/wangjun861205/article/details/129315868