【leetcode】【初级算法】【字符串7】实现strStr()

这篇博客探讨了如何在字符串中寻找子串的方法,包括Python和Java的内置函数实现,以及两种不同的搜索算法:暴力搜索和KMP算法。暴力搜索通过逐个字符比较消耗较多时间,而KMP算法利用预处理的最长公共前后缀数组提高效率,避免了不必要的回溯。文章详细解释了KMP算法的原理和步骤,并提供了相应的代码实现。

题目

实现 strStr() 函数。

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

说明:

当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。

对于本题而言,当 needle 是空字符串时我们应当返回 0 。这与 C 语言的 strstr() 以及 Java 的 indexOf() 定义相符。

作者:力扣 (LeetCode)
链接:https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnr003/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

python题解

class Solution(object):
    def strStr(self, haystack, needle):
        """
        :type haystack: str
        :type needle: str
        :rtype: int
        """
        return haystack.find(needle)

java题解

Java中提供了四中查找方法:
1、int indexOf(String str) :返回第一次出现的指定子字符串在此字符串中的索引。
2、int indexOf(String str, intstartIndex):从指定的索引处开始,返回第一次出现的指定子字符串在此字符串中的索引。
3、int lastIndexOf(String str) :返回在此字符串中最右边出现的指定子字符串的索引。
4、intlastIndexOf(String str, int startIndex):从指定的索引处开始向后搜索,返回在此字符串中最后一次出现的指定子字符串的索引。

class Solution {
    public int strStr(String haystack, String needle) {
        return haystack.indexOf(needle);
    }
}

暴搜

class Solution {
    public int strStr(String haystack, String needle) {
        int n = haystack.length();
        int m = needle.length();
        for(int i =0;i+m<n;i++){
            boolean flag = false;
            for(int j=0;j<m;j++){
                if(haystack.charAt(i+j)!=needle.charAt(j)){
                    flag = false;
                    break;
                }
            }
            if (flag){
                return i;
            }           
        }
        return -1 ;
    }
}

kmp

 # 这里学习了kmp算法.命名是由三位发明者的名字首字母命名
        # kmp算法专门针对再字符串中找模式串的问题.
        # 核心思路:指针从头开始匹配,发现不匹配的元素值,直接跳转到最大前后缀位置,再进行比较.不用移动指向字符串的指针i,只用移动指向模式串的指针j(根据他的\每一位字符的最大前后缀数组next)
				class Solution {
    public int strStr(String haystack, String needle) {
        int n = haystack.length(), m = needle.length();
        if(m==0){
            return 0;
        }
        int[] pi = new int [m];
        for(int i=1,j=0;i<m;i++){
            while(j>0 && needle.charAt(i)!=needle.charAt(j)){
                j = pi[j-1];
            }
            if(needle.charAt(i) == needle.charAt(j)){
                j++;
            }
            pi[i] = j;
        }
        for(int i = 0,j=0;i<n;i++){
            while(j>0 && haystack.charAt(i)!= needle.charAt(j)){
                j = pi[j-1];
            }
            if(haystack.charAt(i) == needle.charAt(j)){
                j++;
            }
            if(j==m){
                return i-m+1;
            }
        }
        return -1;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值