Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
思路:本题就是一个字符串匹配的问题。本人能想到的有
1:暴力穷举法
2:kmp算法
3:BM算法
4:Sunday算法
本题选取最快,时间复杂度最好的Sunday算法。
下面我简单介绍一下Sunday算法
所谓sunday算法也是坏字符的匹配问题,设目标串为string,模式串为pattern。
如果string[i]=pattern[j],i++,j++
如果string[i]!=pattern[j],那就看string[i+pattern.length]的下一位tab位在pattern中是否存在,如果存在,那就将i右移,使之对称,如果不存在,则将i移到tab的下一位。
下面演示一下过程,
假如string="LESSONS TEARNED IN SOFTWARE TE",pattern="SOFTWARE"
第一次循环 L!=S 所以tab=8即T所在的位置 T在pattern中存在,则将其与strin串对齐,如下面
LESSONS TEARNED IN SOFTWARE TE
SOFTWARE
第二次循环N!=S重复上面的步骤。
............一直到找到为止
详细的有图的可以看
http://www.cnblogs.com/lbsong/archive/2012/05/25/2518188.html
代码如下(已通过leetcode)
public class Solution {
public int strStr(String haystack, String needle) {
int tab=0;
int i=0,j=0;
int countj=0;
int counti=0;
int k=0;
while(i<haystack.length()&&j<needle.length()) {
if(haystack.charAt(i)==needle.charAt(j)){
i++;
j++;
counti++;
countj++;
} else {
tab=i-counti+needle.length();
k=j-countj+needle.length()-1;
countj=0;
counti=0;
j=0;
while(k>=j && tab<haystack.length()&&needle.charAt(k)!=haystack.charAt(tab) ) {
k--;
}
if(k==-1) i=tab+1;
else i=tab-(k-j);
}
}
if(j==needle.length()) return tab-k;
else return -1;
}
}