Sunday算法果然很容易理解与实现
/**
* Sunday字符串算法
* @author kevin
* **/
public class SundayUtils {
public static void main(String[] args) {
System.out.println(indexOf("sdfsdf海贼0王","海贼0"));
}
public static String indexOf(String source, String target){
char[] sourceChars = source.toCharArray();
char[] targetChars = target.toCharArray();
int i = 0;
int j = 0;
int matchLen = 0;
while(i < sourceChars.length && j < targetChars.length){
if(j < 0){
j = 0;
}
if(sourceChars[i] == targetChars[j]){
if(j > matchLen){
matchLen = j;
}
i++;
j++;
}else{
//如果不匹配,则主串的索引 : i += targetChars.length - 1 - j + 1; 主串中参加匹配的最末位字符的下一位字符
i += targetChars.length - j;
if(i >= sourceChars.length - 1){
//不匹配
break;
}
j = targetChars.length - 1;
while(j >= 0){
if(sourceChars[i] != targetChars[j]){
j--;
}else{
break;
}
}
}
}
//因为sunday算法是从前往后匹配,所以可以根据从前往后的顺序取模式串的长度
char[] chars = new char[matchLen + 1];
int m = 0;
for(int n = 0; n