public static int indexOf(String Text, String Key, int i) {
char[] Textchars = Text.toCharArray();
char[] Keychars = Key.toCharArray();
int iter_Text, iter_Key;
int Num_Text = Text.length(), Num_Key = Key.length();
int[] Increase = new int[26];
for (int iter_Increase = 0; iter_Increase < Increase.length; iter_Increase++) {
Increase[iter_Increase] = Num_Key + 1;
}
for (iter_Key = 0; iter_Key < Num_Key; iter_Key++) {
Increase[Keychars[iter_Key] - 'a'] = Num_Key - iter_Key;
}
int pos = i;
while(pos < (Num_Text - Num_Key + 1)){
iter_Text = pos;
for (iter_Key = 0; iter_Key < Num_Key; iter_Key++, iter_Text++) {
if (Textchars[iter_Text] != Keychars[iter_Key]) {
pos += Increase[Textchars[pos + Num_Key] - 'a'];
break;
}
}
if (iter_Key == Num_Key) {
return pos;
}
}
return false;
}
代码很简单...思路也很简单...通过ASCII码的性质,在数组Increase建立 字母——增量 之间的映射(有点像map容器中的键值对)。在使用时(遇到不匹配时)根据Increase的增量跃迁匹配串,然后从头开始继续匹配,如此往复,直到找到目标串...
当然了,Sunday算法的核心在于如何构建increase增量数组(这也是string matching algorithm的核心),详情请自行去看paper..
以上..