JAVA-LeetCode is simple 28

1. Title

Implement the strStr() function.

Given a haystack string and a needle string, find the first position (starting from 0) where the needle string appears in the haystack string. If it does not exist, -1 is returned.

Example 1:

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

Input: haystack = "aaaaa", needle = "bba"
Output: -1

Source: LeetCode

Link: Implement strStr

2. Analysis

Double pointer method:
Find the substring in the string. This problem needs to access the string one by one.
First, use the pointer No. 1 to lock the position of the first character of the substring in the parent string,
and then use the pointer 1 on the parent string Sliding, the pointer 1 slides in the substring and compares them one by one .
When only a part of the substring is found, in order to prevent the same character in the substring, the pointer of the parent string needs to be returned to the next digit after the first character of the substring is first found. Continue to compare until the remaining substrings are not enough to express the stop of the target substring, and return -1;

3. Code example

public static int strStr(String haystack,String needle){
    
    
        int L = haystack.length(),l = needle.length();
        if (l==0){
    
    
            return 0;
        }
        int p = 0;
        while (p<L-l+1){
    
    
            while (p<L-l+1 && haystack.charAt(p)!=needle.charAt(0)){
    
    
                p++;

            }
            int pp=0,len=0;
            while (pp<l && p<L && haystack.charAt(p)==needle.charAt(pp)){
    
    
                pp++;
                p++;
                len++;
            }
            if (len==l){
    
    
                return p-len;

            }else{
    
    
                p=p-len+1;
            }
        }
        return -1;

    }

Guess you like

Origin blog.csdn.net/weixin_44712669/article/details/111566867