首页 > 其他 > 详细

算法-KMP

时间:2014-02-27 11:34:46      阅读:511      评论:0      收藏:0      [点我收藏+]

原理:http://www.ruanyifeng.com/blog/2013/05/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm.html

示例:leetcode:Implement strStr()

 

bubuko.com,布布扣
 1 public class Solution {
 2     public String strStr(String haystack, String needle) {
 3 
 4         int i = 0;
 5         int hlength = haystack.length();
 6         int nlength = needle.length();
 7 
 8         if (nlength == 0) {
 9             return haystack;
10         } else {
11             int[] form = KMPform(needle);
12 
13             while (i <= hlength - nlength) {
14                 int j = 0;
15                 while (j < nlength) {
16                     if (haystack.charAt(i + j) != needle.charAt(j)) {
17                         if (j == 0) {
18                             i++;
19                         } else {
20                             i = i + j - form[j - 1]-1;
21                         }
22                         break;
23                     } else if (j == nlength - 1) {
24                         return haystack.substring(i);
25                     }
26                     j++;
27                 }
28             }
29             return null;
30         }
31     }
32     
33     public int[] KMPform(String str) {
34         int[] form = new int[str.length()];
35         form[0] = -1;
36         for (int i = 1; i < form.length; i++) {
37             int index = form[i - 1];
38             while (index >= 0 && str.charAt(i) != str.charAt(index + 1))
39             {
40                 index = form[index];
41             }
42             if (str.charAt(i) == str.charAt(index + 1))
43             {
44                 form[i] = index + 1;
45             }
46             else
47             {
48                 form[i] = -1;
49             }
50         }
51         return form;
52     }
53 
54 }
bubuko.com,布布扣

算法-KMP,布布扣,bubuko.com

算法-KMP

原文:http://www.cnblogs.com/lance-/p/3569471.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!