http://oj.leetcode.com/problems/implement-strstr/
Implement strStr().
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
Returns a pointer to the first occurrence of needle in haystack, or null if needle is not part of haystack.
大海捞针,很贴切,好吧,我用暴力居然直接过了,羞愧....
JDK源码中有实现,就不罗嗦了,下午研究了一下KMP算法(O(M + N)),很不错的算法,明天好好整理一下,重新写一遍,并写一篇关于KMP算法的博文吧。
暴力——O(m*n)代码如下:
public String strStr(String haystack, String needle) {
if(needle == null || needle.length() == 0 || haystack == null){
return haystack;
}
int hayStackLen = haystack.length();
int needleLen = needle.length();
if(hayStackLen < needleLen || (hayStackLen == needleLen && !haystack.equals(needle))){
return null;
}
char first = needle.charAt(0);
int max = hayStackLen - needleLen + 1;
for(int i = 0; i < max; i++){
if(haystack.charAt(i) != first){
while(++i < max && haystack.charAt(i) != first);
}
if(i < max){
int j = i + 1;
int end = j + needleLen - 1;
for(int k = 1; j < end && needle.charAt(k) == haystack.charAt(j); j++,k++);
if(j == end){
return haystack.substring(i);
}
}
}
return null;
}