首页 > 其他分享 >代码随想录训练营|Day 9|28

代码随想录训练营|Day 9|28

时间:2022-09-30 03:11:15浏览次数:66  
标签:index return int 随想录 needle 28 table haystack Day

28. Find the Index of the First Occurrence in a String

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.

KMP的主要思想是当出现字符串不匹配时,可以知道一部分之前已经匹配的文本内容,可以利用这些信息避免从头再去做匹配了。
next数组就是一个前缀表(prefix table)
使用前缀表,就不会从头匹配,而是从上次已经匹配的内容开始匹配
记录下标i之前(包括i)的字符串中,有多大长度的相同前缀后缀。
下标5之前这部分的字符串(也就是字符串aabaa)的最长相等的前缀 和 后缀字符串是 子字符串aa ,因为找到了最长相等的前缀和后缀,匹配失败的位置是后缀子串的后面,那么我们找到与其相同的前缀的后面从新匹配就可以了。

下标i之前(包括i)的字符串中,有多大长度的相同前缀后缀。

找到的不匹配的位置, 那么此时我们要看它的前一个字符的前缀表的数值是多少。
因为要找前面字符串的最长相同的前缀和后缀。所以要看前一位的 前缀表的数值。

/**
 * Using KMP Algorithm
 *
 * Time Complexity: O(M + N). O(N) to create lookup table. O(M) to find the
 * needle in haystack.
 *
 * Space Complexity: O(N). This is required to save the lookup table.
 *
 * M = Length of haystack string. N = length of needle string.
 */
class Solution {
    public int strStr(String haystack, String needle) {
        if (haystack == null || needle == null) {
            return -1;
        }

        int nLen = needle.length();
        int hLen = haystack.length();
        if (nLen == 0) {
            return 0;
        }
        if (hLen == 0) {
            return -1;
        }

        int[] table = kmpLookupTable(needle);
        int i = 0;
        int j = 0;
        while (i < hLen && j < nLen) {
            if (haystack.charAt(i) == needle.charAt(j)) {
                i++;
                j++;
            } else {
                if (j > 0) {
                    j = table[j - 1];
                } else {
                    i++;
                }
            }
        }

        if (j == nLen) {
            return i - j;
        }
        return -1;
    }

    private int[] kmpLookupTable(String s) {
        int[] table = new int[s.length()];
        int i = 1;
        int index = 0;
        while (i < s.length()) {
            if (s.charAt(i) == s.charAt(index)) {
                table[i] = index + 1;
                index++;
                i++;
            } else {
                if (index > 0) {
                    index = table[index - 1];
                } else {
                    table[i] = 0;
                    i++;
                }
            }
        }
        return table;
    }
}

Time Complexity:O(m + n)
Space Complexity:O(1)

For Future References

题目链接:https://leetcode.com/problems/find-the-index-of-the-first-occurrence-in-a-string/

文章讲解: https://programmercarl.com/0028.实现strStr.html

视频讲解:https://www.bilibili.com/video/BV1PD4y1o7nd/
             https://www.bilibili.com/video/BV1M5411j7Xx/

标签:index,return,int,随想录,needle,28,table,haystack,Day
From: https://www.cnblogs.com/bluesociety/p/16743630.html

相关文章

  • 学习 MySQL 需要知道的 28 个小技巧
    如何快速掌握MySQL?培养兴趣兴趣是最好的老师,不论学习什么知识,兴趣都可以极大地提高学习效率。不管学习 MySQL5.7 还是 MySQL8.0 都不例外!夯实SQL基础计算机领......
  • 2022.9.28学习了基础指针
    今天是周四,学校没有课,早上起来学习了一会C语言,今天学了一下基础的指针(印象比较深),对这个东西也有了一个初步的认识,也试着敲了两个代码。毕竟是刚刚开始的的时候嘛,难免有一......
  • day08
    leetcode344反转字符串直接首位设置头尾指针头向右尾向左一边遍历一遍交换classSolution{publicvoidreverseString(char[]s){ intleft=0; int......
  • Java SE 宋红康 days01-查漏补缺
    0.Java相关包java.lang:包含一些Java语言的核心类,如String、Math、Integer、System和Thread等java.net:执行与网络相关操作的类和接口java.io:提供多种输入/......
  • Day13
    内部类*/publicclassOuter{ /*privateintid=10;  publicvoidout(){    System.out.println("这是外部类方法");  } publicclassInner{......
  • Spring源码学习:day2
    前言:我还是太懒了,连截图都懒得粘贴,故直接用书上说的话的截图吧。代码的编写过程都是应该有一个入口的,所有的代码最终都是为了那个入口更加方便更加简单而产生的。......
  • Spring 源码学习:day1
    前言:最近也不知道该忙些什么样的事情。便随便看看源码算了。正文:(1)在网上下载Spring的源码:可以采用git方式下载 https://github.com/spring-projects/s......
  • 学习python-Day66
    今日学习内容前后端开发模式API接口postman使用序列化和反序列化restful规范drf:第三方app>>>快速实现符合restful规范的接口视图类,都是继承APIView......
  • 做题记录整理dp15 P1772. [ZJOI2006] 物流运输(2022/9/28)
    P3648[APIO2014]序列分割第一次做斜率优化的题题解看懂了,但没有完全看懂等以后得回来看一次#include<bits/stdc++.h>#definefor1(i,a,b)for(inti=a;i<=b;i++)......
  • day7 - 用户交互
    scanner用scanner类获取用户的输入Scanners=newScanner)(System.in);通过next()和nextline()获取输入字符串通过hasNext()和hasNextLine()判断是否还有输入的数据 凡是......