LeetCode.28. Implement strStr()

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiakexiaohu/article/details/79443506

题目:

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

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

Example 2:

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

分析:

   
   
   

class Solution {
    public int strStr(String haystack, String needle) {
        //字符串匹配,利用KMP算法进行求解。
        //思路:KMP算法是每次回退到模式串相同的位置
        
        if(haystack.length()==0&&needle.length()==0){
            return 0;
        }
        
        if(haystack.length()==0&&needle.length()!=0){
            return -1;
        }
        int i=0,j=0;
        //用来存储每次回退的长度
        int [] next=new int[needle.length()+1];
        //计算模式串中个下标回退长度
        getNext(needle,next);
        
        while(i<haystack.length()&&j<needle.length()){
            if(j==-1||haystack.charAt(i)==needle.charAt(j)){
                i++;
                j++;
            }else{
                //不相等,回退,直到回退到相等位置
                j=next[j];
            }
        }
        //判断j是否查找结束
        if(j==needle.length()){
            return i-needle.length();
        }
        
        return -1;
    }
    public void getNext(String needle,int [] next){
        //前面的指针
        int k=-1;
        //后面匹配的指针
        int j=0;
        //第一个位置回退设置为-1
        next[0]=-1;
        while(j<needle.length()-1){
            //因为需要j++所以只需要判断到length-1
            if(k==-1||needle.charAt(k)==needle.charAt(j)){
                //说明开始匹配,k和j分别后移一位
                k++;
                j++;
                //判断是否相等
                if(needle.charAt(k)==needle.charAt(j)){
                    //相等就更新回退值
                    next[j]=next[k];
                }else{
                    //不相等,则重新赋值k个已经重复的值
                    next[j]=k;
                }
            }else{
                //匹配失败,k回退
                k=next[k];
            }
        }
        
    }
}

猜你喜欢

转载自blog.csdn.net/xiakexiaohu/article/details/79443506