Kmp简单运用

一个简单的题,复习一下KMP

对于两个字符串A,B。请设计一个高效算法,找到B在A中第一次出现的起始位置。若B未在A中出现,则返回-1。

给定两个字符串AB,及它们的长度lenalenb,请返回题目所求的答案。

测试样例:
"acbc",4,"bc",2
返回:2

 1 import java.util.*;
 2 
 3 public class StringPattern {
 4     public int findAppearance(String A, int lena, String B, int lenb) {
 5         // write code here
 6         return kmp(A,lena,B,lenb);
 7     }
 8     private int kmp(String A,int m,String B,int n){
 9         if(A==null||B==null||m==0||n==0) return -1;
10         int[] next=new int [n];
11         makeNext(B,next);
12         int j=0;
13         for(int i=0;i<m;i++){
14             while(j>0&&A.charAt(i)!=B.charAt(j))  //j>0表明此时前面已经有匹配成功的,只是此处不同,所以保持和前面一致
15                 j=next[j-1];
16             if(A.charAt(i)==B.charAt(j))
17                 j++;
18             if(j==n)
19                 return i-j+1;
20         }
21         return -1;
22         
23     }
24     public void makeNext(String B,int []next){
25         //构造next表,如对于ABCDAB 为 0 0 0 0 1 2
26         //相当于对自己把自己同时当成文本串和字符串进行比较,字符串向后移动,每次都从0开始,有相同的就加1 开始比较下一位
27         //没有相同的就保持和原来一样
28         next[0]=0;
29         int j=0;
30         for(int i=1;i<B.length();i++){
31             while(j>0&&B.charAt(i)!=B.charAt(j))
32                 j=next[j-1];
33             if(B.charAt(i)==B.charAt(j))
34                 j++;
35             next[i]=j;
36         }
37     }
38 }

猜你喜欢

转载自www.cnblogs.com/pathjh/p/9000648.html