public class Demo04 {
public static void main (String[] args) {
int pos = bf("ccnu ylpgogo... yes. ." , "12ypl1" );
System.out .println(pos);
int pos1 = bf1("I am a boy." , "bo" );
System.out .println(pos1);
int pos2 = kmp("I am a girl." , "girl" );
System.out .println(pos2);
int [] next = getNext("ababaaaba" );
for (int i : next) {
System.out .print(i + " " );
}
}
public static int bf (String s, String p){
if (s == null || p == null || s.length() == 0 || p.length() == 0 ){
return -1 ;
}
if (s.length() < p.length()){
return -1 ;
}
int sLen = s.length();
int tLen = p.length();
for (int i = 0 ; i < (sLen - tLen + 1 ); i++){
for (int ii = 0 ; ii < tLen; ii++){
if (s.charAt(i + ii) != p.charAt(ii)){
break ;
}
if (ii == tLen - 1 ){
return i;
}
}
}
return -1 ;
}
public static int bf1 (String s, String p) {
if (s == null || p == null || s.length() == 0 || p.length() == 0 ) {
return -1 ;
}
if (s.length() < p.length()) {
return -1 ;
}
int sLen = s.length();
int pLen = p.length();
int iS = 0 ;
int iP = 0 ;
while (iS < (sLen - pLen + 1 ) && iP < pLen) {
if (s.charAt(iS) == p.charAt(iP)) {
iS++;
iP++;
} else {
iS = iS - iP + 1 ;
iP = 0 ;
}
}
if (iP == pLen) {
return iS - iP;
} else {
return -1 ;
}
}
public static int kmp (String s, String p){
if (s == null || p == null || s.length() == 0 || p.length() == 0 ){
return -1 ;
}
if (s.length() < p.length()){
return -1 ;
}
int [] next = getNext(p);
int sLen = s.length();
int pLen = p.length();
int i = 0 ;
int j = 0 ;
while (i < sLen && j < pLen){
if (j == -1 || s.charAt(i) == p.charAt(j)){
i++;
j++;
}else {
j = next[j];
}
}
if (j == pLen){
return i - j;
}else {
return -1 ;
}
}
public static int [] getNext (String t){
int [] next = new int [t.length()];
int i = -1 ;
int j = 0 ;
next[j] = -1 ;
while (j < t.length() - 1 ){
if (i == -1 || t.charAt(i) == t.charAt(j)){
i++;
j++;
next[j] = i;
}else {
i = next[i];
}
}
return next;
}
}