问题描述
Implement strStr().
Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
题目链接:28. Implement strStr()
Example1:
Input: haystack = “hello”, needle = “ll”
Output: 2
Example2:
Input: haystack = “aaaaa”, needle = “bba”
Output: -1
思路分析
实现string的strStr()方法,原型:char *strstr(const char *str1, const char *str2)
题目要求返回第二个字符串在第一个字符串中第一次出现的位置,如果第一个字符串不包含第二个字符串,则返回-1。首先要明确第二个字符串弱为空,那它在第一个位置就出现了,应返回0;然后就循环比较haystack中的每一个字符,从它开始的needle.length()个字符是否与needle相同;如果循环结束还没有相同的,就返回-1。
代码
class Solution {
public:
int strStr(string haystack, string needle) {
int count, index;
if (needle.length() == 0)
return 0;
for (int i = 0; i < haystack.length(); i++){
count = 0;
for(int j = 0; j < needle.length(); j++){
if (haystack[i+j] != needle[j])
break;
else
count++;
}
if (count == needle.length()){
index = i;
return index;
}
}
return -1;
}
};
时间复杂度:O(mn) //m为haystack长度,n为needle长度。
//官方玩梗啊,find a needle in a haystack == 大海捞针
反思
if判断之后的语句超过一行要加花括号啊,不是第一次吃这种亏了。还有读不懂题也是很伤,看清楚要返回什么。cplusplus还是一个神级网站的,要多逛逛。
然而这个算法,实在是太慢了,非常不简洁,范例代码:
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++) {//最后的n-1个字符没有比较的必要
int j = 0;//替代了count的作用,还加入了循环
for (; j < n; j++)
if (haystack[i + j] != needle[j])
break;
if (j == n) return i;//如果循环能顺利完成则可以返回index了
}
return -1;
}
};
还有更经典的KMP“看毛片”算法
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.length(), n = needle.length();
if (!n) return 0;
vector<int> lps = kmpProcess(needle);
for (int i = 0, j = 0; i < m; ) {
if (haystack[i] == needle[j]) {
i++;
j++;
}
if (j == n) return i - j;
if (i < m && haystack[i] != needle[j]) {
if (j) j = lps[j - 1];
else i++;
}
}
return -1;
}
private:
vector<int> kmpProcess(string& needle) {
int n = needle.length();
vector<int> lps(n, 0);
for (int i = 1, len = 0; i < n; ) {
if (needle[i] == needle[len])
lps[i++] = ++len;
else if (len) len = lps[len - 1];
else lps[i++] = 0;
}
return lps;
}
};