28题

Leetcode第28题


用暴力法会 超时。所以重新学了遍 KMP算法

暴力法:

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算法:

首先是求解next数组。next数组的含义:next[i] 代表不包含i的前面串的最长相同前后缀长度。因此next数组长度是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;
发布了21 篇原创文章 · 获赞 0 · 访问量 87

猜你喜欢

转载自blog.csdn.net/weixin_43963453/article/details/105346684
28-
28
今日推荐