您的位置:首页 > 其它

hihocoder 1015 KMP

2015-09-13 10:44 288 查看
写一个KMP算法发了我大半天的时间。其实写的时候真是发现自己的逻辑不如别人的逻辑清晰,牛人的代码一行能实现的功能我却要好几行代码。

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.util.Scanner;

public class Main3{

public static void main(String[] args){

Scanner sc=new Scanner(System.in);

int n=sc.nextInt();

while(n>0){

String pattern=sc.next();

String source=sc.next();

int num=getMatchNumber(source,pattern);

System.out.println(num);

n--;

}

}

public static int getMatchNumber(String str1,String str2){

if(str1==null||str2==null)

return 0;

char[] ch1=str1.toCharArray();

char[] ch2=str2.toCharArray();

int len1=ch1.length;

int len2=ch2.length;

int count=0;

int[] next=getNext(ch2);

int i=0,j=0;

while(i<len1){

if(j==-1||ch1[i]==ch2[j]){

i++;

j++;

}

else{

j=next[j];

}

if(j==len2){ //这个地方考虑了我很长时间。这个题目不仅要是查看字符串是否匹配,而且是要找出匹配的次数。如果当一个字符串匹配成功一次之后,那么模式串往前挪的位置使得i-1位置对应next[j-1]位置继续比较,而不能是i位置和next[j-1]+1位置,因为存在j=-1的情况。

count++;

i--;

j=next[j-1];

}

}

return count;

}

//获取next数组,next数组表示,当前原字符串i位置字符与模式中第j个位置的字符匹配失败之后,i位置应该与next[j]位置的字符串进行比较。next[0]=-1,如果为-1,则表示没有可以匹配的位置,字符串和模式串都要往前走。

public static int[] getNext(char[] ch){

if(ch==null)

return null;

int len=ch.length;

int[] next=new int[len];

int i=0,j=-1;

next[0]=-1;

while(i<len-1){

if(j==-1||ch[i]==ch[j])

next[++i]=++j;

else

j=next[j];

}

return next;

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: