KMP Algorithm Implementation(JAVA)



/*

 * char has a wrap class called 'Character'.

 *function 'toLowerCase' belongs to class 'Character'.

 *function 'charAt(int i)' returns a result in char.

 * */

 

public class Kmp {

public int stringMatch(String x,String y,boolean flag) {

int[] pp = patternParse(y,flag);

boolean tip = false;

int result = -1;

int mark = 0;

int lenx = x.length();

int leny = y.length();

int i = 0;

int j = 0;

if( leny > lenx ) {

return -2;

}

while( j < leny || i <= lenx -leny ) {

char tempx = flag?Character.toLowerCase( x.charAt( i ) ):x.charAt( i );

char tempy = flag?Character.toLowerCase( y.charAt( j ) ):y.charAt( j );

if ( tempx == tempy ) {

++i;

++j;

}

else {

if ( j == 0  ) {

++i;

++j;

}

else {

j = pp[j-1];

}

    }

if ( j == leny ) {

mark = i;

break;

}

if ( i == lenx ) {

break;

}

}

if ( mark != 0 ) {

result = mark - leny;

}

return result;

}

public int[] patternParse(String x,boolean flag) {

int len = x.length();

int[] pp = new int[len];

pp[0] = 0;

int i  = 0;

int j  = 1;

while( j < len ) {

char tempf = flag?Character.toLowerCase( x.charAt( i ) ):x.charAt(i);

char templ = flag?Character.toLowerCase( x.charAt( j ) ):x.charAt(j);

if( tempf == templ ) {

pp[j] = pp[i] + 1;

++i;

++j;

}

else {

pp[j] = 0;

i = pp[i];

++j;

}

}

return pp;

}

public static void main(String [] args) {

int a = new Kmp().stringMatch("abcabcdaYdaabcabcac", "abcday", true);

System.out.println(a);

}

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值