Implement strStr().
Returns the index of the first occurrenceof needle in haystack, or -1 if needle is not part of haystack.
实现子字符串查找功能。
犹记得清华大学出版社的数据结构书上,那神奇的KMP算法……
KMP请自行百度。
这里我用了BM算法(只用到了delta1),BM算法也请自行百度。这两个算法的图解太难用电脑绘制。
我也怕自己讲不好。Σ(・ω・;|||
我用的参考书是国外计算机经典教材的C++数据结构与算法。
直接贴源码了。
一开始随便来了个暴力解法,直接超时了。。。顺便,这道题你可以直接这样来测试string.find()的速度:
Leetcode的AcceptedSolutions Runtime Distribution(15-06-08)
源码:(VS2013)
#include <iostream>
#include <map>
#include <array>
using namespace std;
int strStr(string haystack, string needle);
int main(){
cout << strStr("mississippi", "pi");
return 0;
}
int strStr(string haystack, string needle){
//
//BM算法(only delta1)
if (0 == haystack.size() && 0 == needle.size()) return 0;
if (0 == haystack.size()) return -1;
if (0 == needle.size()) return 0;
int i = 0;
int haystackSize = haystack.size();
int needleSize = needle.size();
int delta[26] = { needleSize, needleSize, needleSize, needleSize, needleSize,
needleSize, needleSize, needleSize, needleSize, needleSize,
needleSize, needleSize, needleSize, needleSize, needleSize,
needleSize, needleSize, needleSize, needleSize, needleSize,
needleSize, needleSize, needleSize, needleSize, needleSize,
needleSize };
for (i = 0; i < needleSize; i++)
{
delta[(int)needle[i] - 97] = needleSize - i - 1;
}
i = needleSize - 1;
int j;
while (i < haystackSize)
{
j = needleSize - 1;
while (j >= 0 && haystack[i] == needle[j])
{
i--;
j--;
}
if (-1 == j)
{
return i + 1;
}
int offset = delta[(int)haystack[i] - 97];
i = i + ((offset > (needleSize - j)) ? offset : (needleSize - j));
}
return -1;
}