Leetcode beginner - to achieve strStr ()

topic

This question is very simple, but we have to note that, do not call the original function of the system, which will make this question becomes meaningless

 

Code offer:

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

Results are as follows:

Published 26 original articles · won praise 3 · Views 515

Guess you like

Origin blog.csdn.net/qq_39377543/article/details/104091207