zoukankan      html  css  js  c++  java
  • KMP算法

    什么是KMP?

    KMP算法要解决的问题就是在字符串(也叫主串)中的模式(模式串)定位问题。说简单点就是我们平时常说的关键字搜索。

     传统的关键字搜索算法当模式串当前字符与主串当前匹配字符不等时,主串指针需要回溯至开始比较的首位的下一位,模式串指针归零。

    KMP算法就是解决了主串指针回溯的问题。

     1 public class KMP {
     2 
     3     public static int KMP(String str1, String str2) {
     4         int len1 = str1.length(); // str1的长度 主串
     5         int len2 = str2.length();// str2的长度 模式串
     6         char[] arr1 = str1.toCharArray(); // 字符串转成字符数组
     7         char[] arr2 = str2.toCharArray();
     8         int[] next = new int[len2]; // next 存放 str[i]!= sre2[j]时 j的下个位置
     9         next = next(arr2);
    10         int i = 0; // 主串指针
    11         int j = 0;// 模式串指针
    12         while (j < len2 && i < len1) {
    13 
    14             if (j == -1 || arr1[i] == arr2[j]) {
    15                 i++;
    16                 j++;
    17             } else {
    18                 j = next[j];
    19             }
    20         }
    21 
    22         if (j == len2) {// 主串含有模式串返回主串中模式串第一个字符的位置
    23             return i - j;
    24         } else {// 不含有返回-1
    25             return -1;
    26         }
    27     }
    28 
    29     public static int[] next(char[] arr) { // 当主串str1[i]!= 模式串 str2[j] 时 j
    30                                             // 应指向的位置 next[j]
    31         int len = arr.length;
    32         int next[] = new int[len];
    33         next[0] = -1;
    34         int k = -1;
    35         int j = 0;
    36         while (j < len - 1) {
    37             if (k == -1 || arr[j] == arr[k]) {
    38                 next[++j] = ++k;
    39             } else {
    40                 k = next[k];
    41             }
    42         }
    43         return next;
    44     }
    45 
    46     public static void main(String[] args) {
    47         String str1 = "jiaorenzhan";
    48         String str2 = "ren";
    49         int index = KMP(str1, str2);
    50         System.out.println(index);
    51     }
    52 }
  • 相关阅读:
    springmvc 处理静态资源
    springmvc jsp 获取 上下文
    springmvc 如何设置首页
    servlet-mapping url-pattern / 和 /*区别
    nginx支持php
    openresty 变量
    git tag用法
    python 导入模块,__init__.py 的作用
    python 转码问题
    python装饰器
  • 原文地址:https://www.cnblogs.com/jiaorenzhan/p/10647962.html
Copyright © 2011-2022 走看看