/*
* 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);
}
}