Leetcode double pointer to achieve strStr () java

Title description
Implement the strStr() function.
Given a haystack string and a needle string, find the first position of the needle string in the haystack string (starting from 0). If it does not exist, return -1
Example 1:
Input: haystack = "hello", needle = "ll"
Output: 2

Idea:
Only when the first character of the substring is the same as the first character of the needle string does it need to be compared. Then it compares character by character, and terminates as soon as it does not match. When a mismatch is found, the backtracking starts. It should be noted that the pn pointer is moved to the position of pn = pn-curr_len + 1, not the position of pn = pn-curr_len.

Code:

class Solution {
    
    
    public int strStr(String haystack, String needle) {
    
    
        int lenH = haystack.length();
        int lenN = needle.length();
        if(lenN == 0){
    
    
            return 0;
        }
        int start = 0;
        while(start < lenH - lenN +1){
    
    
            while(start < lenH - lenN +1 && haystack.charAt(start) != needle.charAt(0)){
    
    
                start++;
            }
            int start_n = 0;
            int currentlen = 0;
            while(start < lenH && start_n < lenN && haystack.charAt(start) == needle.charAt(start_n)){
    
    
                start_n++;
                start++;
                currentlen++;
            }
            if(currentlen == lenN){
    
    
                return start - currentlen;
            }
            start = start - currentlen +1;
        }
        return -1;

    }
}

Guess you like

Origin blog.csdn.net/stonney/article/details/112140824