28 questions

Leetcode question 28


Violence will use a timeout . So I learned the KMP algorithm again .

Violence law:

public int strStr(String haystack, String needle) {
        if(needle == null || needle.length() == 0)
            return 0;//题目要求空模式串返回0,不写会报错。
        int i,j;
    
        for(i = 0;i < haystack.length();i++)//回溯遍历
          {
                j = 0;
                int start = i;
                while(start < haystack.length() &&  j < needle.length() && haystack.charAt(start) == needle.charAt(j)){
                ++j;
                ++start;
                }
                if( j == needle.length())
                    return i;

            }
        return -1;
    }

KMP algorithm:

The first is to solve the next array. The meaning of the next array: next [i] represents the longest same prefix and suffix length of the previous string that does not contain i. Therefore, the length of the next array is len + 1 .

//求解next数组。needle是模式串。长度位len2。其实是个动态规划的题。
 int[] next = new int[len2 + 1];
        next[0] = -1;//边界条件
        int j = 0,i = -1;
       while(j < len2){
            if(i == -1 || needle.charAt(i) == needle.charAt(j)){
                ++i;
                ++j;
                next[j] = i;
            }
            else 
                i = next[i];
        }
 i = 0;
        j = 0;
        while(i < len1 && j < len2){
            if(j == -1 || haystack.charAt(i) == needle.charAt(j)){
                ++i;
                ++j;
            }else{
                j = next[j];
            }
        }
        if(j == len2)
            return i - j;
        return -1;
Published 21 original articles · praised 0 · visits 87

Guess you like

Origin blog.csdn.net/weixin_43963453/article/details/105346684
28