【LeetCode】#28 implement strStr(). (Java solution + icon)

Implement strStr()

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, it returns -1.

示例 1:

输入: haystack = "hello", needle = "ll"
输出: 2
示例 2:

输入: haystack = "aaaaa", needle = "bba"
输出: -1

Description:

When needle is an empty string, what value should we return? This is a good question in an interview.

For this question, we should return 0 when needle is an empty string. This is consistent with the definition of strstr() in C language and indexOf() in Java.

Problem-solving idea:
For this problem, you can imagine that the needle string is fixed first, and the first character of the haystack string is compared with the first character of the needle string. If it is not equal, the haystack string is moved forward and compared to the next one. If it is equal, it starts. Comparing the corresponding characters in the haystack string in the needle string, it is found that there are repeated haystack string forward steps that do not meet the conditions, and so on.
Illustration:
Insert picture description hereJava code

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

Guess you like

Origin blog.csdn.net/qq_45621376/article/details/111914709