[算法]实现strStr()

我的知乎:DarrenChan陈驰

 

正文

题目#

实现 strStr() 函数。

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回  -1。

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/implement-strstr
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

思路#

两种解法。

第一种:暴力直接求解,时间复杂度是O(n^2)。

第二种:Rabin-Karp算法。

时间复杂度O(m + n)。

代码#

代码1#

复制代码
class Solution {
    public int strStr(String haystack, String needle) {
        if(haystack == null || needle == null) return -1;
        for(int i=0; i < haystack.length() - needle.length() + 1; i++){
            int j = 0;
            for(; j < needle.length(); j++){
                if(haystack.charAt(i + j) != needle.charAt(j)) break;
            }
            if(j == needle.length()) return i;
        }
        return -1;
    }
}
复制代码

代码2#

复制代码
class Solution {
    static final int BASE = 1000000;
    public int strStr(String haystack, String needle) {
        if(haystack == null || needle == null) return -1;
        if(needle.length() == 0) return 0;

        int m = needle.length();
        //31 ^ m
        int power = 1;
        for (int i = 0; i < m; i++) {
            power = (power * 31) % BASE;
        }

        int targetCode = 0;
        for (int i = 0; i < m; i++) {
            targetCode = (targetCode * 31 + needle.charAt(i)) % BASE;
        }

        int hashCode = 0;
        for (int i = 0; i < haystack.length(); i++) {
            hashCode = (hashCode * 31 + haystack.charAt(i)) % BASE;
            if(i < m - 1){
                continue;
            }

            //减去开始的数 abcd - a
            if(i >= m) {
                hashCode = hashCode - (haystack.charAt(i - m) * power) % BASE;
                if(hashCode < 0){
                    hashCode += BASE;
                }
            }

            //双重校验
            if(hashCode == targetCode){
                if(haystack.substring(i - m + 1, i + 1).equals(needle)){
                    return i - m + 1;
                }
            }
        }

        return -1;
    }
}
复制代码

 

posted @   DarrenChan陈驰  阅读(728)  评论(0编辑  收藏  举报
编辑推荐:
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 周边上新:园子的第一款马克杯温暖上架
CONTENTS

喜欢请打赏

扫描二维码打赏

了解更多

点击右上角即可分享
微信分享提示