编号28: 实现 strStr()

编号28: 实现 strStr()

给定一个 haystack 字符串和一个 needle 字符串,在 haystack 字符串中找出 needle 字符串出现的第一个位置 (从0开始)。如果不存在,则返回 -1。

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

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

说明:
当 needle 是空字符串时,我们应当返回什么值呢?这是一个在面试中很好的问题。
对于本题而言,当 needle 是空字符串时我们应当返回 0 。

思路

构造next数组

「构造next数组其实就是计算模式串s,前缀表的过程。」 主要有如下四步:

  1. 初始化
  2. 处理前后缀不相同的情况
  3. 处理前后缀相同的情况
  4. 给next数组赋值

使用next数组来做匹配

使用next数组做匹配跟构造next很相似」** 主要有如下四步:

  1. 初始化
  2. 处理前后缀不相同的情况
  3. 处理前后缀相同的情况
  4. 当str2的长度等于J时,说明以匹配上,返回i-j+1;

代码

public class KMP算法 {
    public static void main(String[] args) {
        String str1 = "BBC ABCDAB ABCDABCDABDE";
        String str2 = "ABCDABD";

        int[] next = kmpNext1(str2);
        String s = Arrays.toString(next);
        System.out.println(s);

        int i = searchString2(str1, str2, next);
        System.out.println(i);


    }
    //复习 得到Next数组-即前缀表
    public static int [] kmpNext1( String str2 ){
        char[] chars = str2.toCharArray();
       int[] next = new int[str2.length()];
       int i = 0;//表示后缀的下标
       int j = 0;//表示前缀的下表
        next [0] = 0;
       for ( i = 1; i < chars.length ; i++) {
            //当两个字符串不相等时
           while( j > 0 && str2.charAt(i) != str2.charAt(j) ){
               j = next[j-1];
           }
           if( str2.charAt(i) == str2.charAt(j) ){
               j++;
           }

           next[i] = j;
        }
        return next;
    }

    //复习 KMP搜索算法
    public static int searchString2(String str1,String str2,int [] next){
        if(str2 == null || str2 == " "){
            return 0;
        }
        char[] chars1 = str1.toCharArray();
        char[] chars2 = str2.toCharArray();

        for (int i = 0, j = 0; i < chars1.length; i++) {
            while (j > 0 && chars1[i] != chars2[j]) {
                j = next[j-1];
            }
            if( chars1[i] == chars2[j] ){
                j++;
            }
            if(chars2.length == j){
                return i-j+1;
            }
        }
        return -1;
    }
}


posted @ 2021-03-15 15:46  胡木杨  阅读(53)  评论(0)    收藏  举报