Implement strStr().
Returns the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
这道题目主要有这三种方法。在Leetcode上并没有展现KMP和BM算法的优势,应该与OJ的测试样例有关;
暴力解法时间复杂度 O(MN), KMP 为 O(M+N), BM 为 O(N/M)
暴力解法:
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length(), n = needle.length();
if (!n) return 0;
for (int i = 0; i < m - n + 1; i++) {
int j = 0;
for (; j < n; j++)
if (haystack[i + j] != needle[j])
break;
if (j == n) return i;
}
return -1;
}
};
KMP算法:
int strStr(string haystack, string needle) {
int nsize = needle.size();
int hsize = haystack.size();
if (nsize == 0) return 0;
int *table = new int[nsize];
memset(table, 0, sizeof(int)*nsize);
//building match table
for (int i = 1, j = 0; i < nsize - 1;){
if (needle[i] != needle[j]){
if (j>0){
j = table[j - 1];
}
else{
i++;
}
}
else{
table[i] = j + 1;
i++;
j++;
}
}
//matching
for (int i = 0, match_pos = 0; i < hsize;){
if (haystack[i] == needle[match_pos]){
if (match_pos == nsize - 1){
return i - (nsize - 1);
}
else{
i++;
match_pos++;
}
}
else{
if (match_pos == 0){
i++;
}
else{
match_pos = table[match_pos - 1];
}
}
}
delete[]table;
return -1;
}
BM算法:
public class Solution {
public String strStr(String haystack, String needle)
{
if(haystack== null) return null;
if(needle==null || needle.length()==0) return haystack;
if(needle.length()>haystack.length()) return null;
int pat_length = needle.length();
int right[] = new int[256];
for(int i=0;i<256;i++)
right[i] =-1;
for(int i=0;i<pat_length;i++)
right[needle.charAt(i)] =i;
int rtn = search(right,haystack,needle);
if(rtn == haystack.length()) return null;
else
return haystack.substring(rtn);
}
public int search(int[] right, String haystack,String needle)
{
int M = haystack.length();
int N = needle.length();
int i,j;
int skip =0;
for(i=0; i<=M-N; i+=skip)
{
skip =0;
for(j=N-1;j>=0;j--)
{
if(needle.charAt(j)!=haystack.charAt(i+j))
{
skip = j-right[haystack.charAt(j+i)];
if(skip<=0) skip=1;
break;
}
}
if(skip ==0) return i;
}
return M;
}