LeetLode eighth day 28. Implement strStr() (with link to explain KMP algorithm)

The LeetCode 100-day foundation building series is mainly for practicing basic data structures and algorithms. The question bank is all LeetCode simple questions (medium and difficult questions will be updated in other series later), mainly written in C language and Java, and the previous questions can be completed. For the purpose of function, better algorithms and optimized code blocks will be used later.
28. Implement strStr()
Implement the strStr() function.
Given two strings haystack and needle, please find the first position of the string needle in haystack string (subscript starts from 0). Returns -1 if not present.

Explanation:
What should we return when needle is an empty string? This is a great question to ask in an interview.
For this question, we should return 0 when needle is an empty string. This matches the definition of strstr() in C and indexOf() in Java.

Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2

Example 2:
Input: haystack = "aaaaa", needle = "bba"
Output: -1
28. Implement strStr()

Java:

class Solution {
    
    
    public int strStr(String haystack, String needle) {
    
    
        int i = 0, j = 0;       
        while(i < haystack.length() && j < needle.length()){
    
    
            if(haystack.charAt(i) == needle.charAt(j)){
    
    
                i++;
                j++;
            }else {
    
    
                i = i - (j - 1);
                j = 0;
            } 
        }
        if(j == needle.length()) return i - j;
        else return -1;
    }
}

[Code Caprice] Explanation of KMP Algorithm

【Miyashui Mitsuha】KMP algorithm with simple questions

C language:

int strStr(char * haystack, char * needle){
    
    
    int len1 = strlen(haystack);
    int len2 = strlen(needle);
    if (len2 == 0) {
    
    
        return 0;
    }
    int next[len2];
    getNext(next, needle);
    int j = -1;
    for(int i = 0; i < len1; i++){
    
    
        while(j >= 0 && haystack[i] != needle[j + 1]){
    
    
            j = next[j];
        }
        if(haystack[i] == needle[j + 1]){
    
    
            j++;
        }
        if(j == (len2 - 1)){
    
    
            return(i - len2 + 1);
        }
    }
    return -1;
}
void getNext(int* next, char* s){
    
       
    int j = -1;
    next[0] = j;
    for(int i = 1; i < strlen(s); i++){
    
    
        while(j >= 0 && s[i] != s[j + 1]){
    
    
            j = next[j];
        }
        if (s[i] == s[j + 1]){
    
    
            j++;
        }
        next[i] = j;
    }
}

Guess you like

Origin blog.csdn.net/qq_43310387/article/details/124042030