0%

实现strStr()

#Question
  Implement strStr().Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.
Clarification:
  What should we return when needle is an empty string? This is a great question to ask during an interview.

  For the purpose of this problem, we will return 0 when needle is an empty string. This is consistent to C’s strstr() and Java’s indexOf().

Example1:

Input: haystack = “hello”, needle = “ll”
Output: 2

Example2:

Input: haystack = “aaaaa”, needle = “bba”
Output: -1

Example3:

Input: haystack = “”, needle = “”
Output: 0

Answer

##思路一:
  两个字符长度相减+1得到的长度就是需要比较的长度,当needle长度为0时,返回0。当haystack与needle不匹配时,返回-1。当haystack与needle匹配时,返回i的值。时间复杂度为O($n^{2}$),空间复杂度为O(n),具体代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
int strStr(string haystack, string needle) {
int m = haystack.size();
int n = needle.size();
int r = m - n + 1;

if (n == 0) return 0;

for (int i = 0 ; i < r; i++) {
int j = i,k = 0;
while (k < n && haystack[j] == needle[k])
k++,j++;
if (k == n) return i;
}

return -1;
}
};

##思路二:
  KMP(字符串查找算法),lps是needle的索引。这里使用的kmp算法,把needle作为kmp前缀,来进行字符比对。如果字符相同,那么len增加。如果不相等,就要看len的值,如果len的值为0那么就将lps[i]的值设置为0。如果len不为零,那么就把lps[len-1]的值赋给len,这一步是为了防止对应字符中间出现了不相等的,将字符串右移。时间复杂度为O(n);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
int strStr(string haystack, string needle) {
if (needle.empty()) return 0;

string kmp = needle + "#" + haystack;
int m = kmp.size(),n = needle.size();
vector<int> lps(m,0);

for (int len = 0,i = 1; i < m;) {
if (kmp[len] == kmp[i]) {
lps[i] = ++len;
if (len == n)
return i - 2 * n;
++i;
}
else if (len == 0)
lps[i++] = 0;
else
len = lps[len - 1];
}
return -1;
}
};