- 今天看到一个新的模式串匹配算法,比我在课堂上学的那个KMP简单多了,而且很好理解啊,就是写的时候要特别注意索引的变化,千万不能写错哟!
public class Solution {
public int strStr(String haystack, String needle) {
if(haystack==null||haystack.length()<needle.length()){
return -1;
}
if(haystack.length()==0||needle.length()==0){
return 0;
}
int i = 0;
int j = 0;
while(i<haystack.length()){
if(haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
}else{
int index = i+needle.length()-j;
int occure;
if(index>=haystack.length()){
return -1;
}else{
occure = needle.lastIndexOf(haystack.charAt(index));
}
if(occure==-1){
i = index + 1;
}else{
i = index -occure;
}
j = 0;
}
if(j==needle.length()){
return i-needle.length();
}
}
return -1;
}
}
- 重点是两个移动:若下一位不在模式串中,则i直接移动到Index的下一位,若下一位在模式串中的occure,则i移动到Index-occure的位置(保证index元素和模式串中occure元素对齐)。并且注意找occure时是反向找的,嗯,就酱紫。