28. Implement strStr() - LeetCode

28. Implement strStr()

Implement strStr().

Return the index of the first occurrence of needle in haystack, or -1 if needle is not part of haystack.

Example 1:

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

Example 2:

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

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()).

Solution1:

two pointers, 放在while循环中

// Time:O(n*m), Space:O(1)
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.length(), m = needle.length();
if (!m) return 0;

int i = 0, j = 0;
while (i < n) {
if (haystack[i] == needle[j]) {
int ok = 1, k = i;
while (k < n && j < m) {
if (haystack[k++] != needle[j++]) {
ok = 0; break;
}
}
if (ok && j == m && k <= n)
return i;
j = 0;
}
i++;
}
return -1;
}

};

Solution2:

for循环, j作为needle的下标, i作为判断的头指针, i+j是haystack的下标,

  • 1, 若两个指针指向的字符不同, 推出内层循环;
  • 2, 如果j能够在上述条件下, 到达哨兵位置, 表明完全匹配;
  • 3, 如果i+j到了haystack的哨兵位置, 扫描结束, 未找到;
// Time:O(n*m), Space:O(1)
class Solution {
public:
int strStr(string haystack, string needle) {
for (int i = 0; ; i++) {
for (int j = 0; ; j++) {
if (j == needle.length()) return i;
if (i+j == haystack.length()) return -1;
if (haystack[i+j] != needle[j]) break;
}
}
}
};

根据这个思路, 对Solution1进行简化,

  • 用达到哨兵位置取代对ok变量的操作;
  • 用i+j取代新增的k变量;
  • i的范围在n-m之内.
// 第一个版本的简化版本
// Time:O(n*m), Space:O(1)
class Solution {
public:
int strStr(string haystack, string needle) {
int n = haystack.length(), m = needle.length();
if (!m) return 0;

int i = 0, j = 0;
while (i <= n-m) {
if (haystack[i] == needle[j]) {
while (j < m && haystack[i+j] == needle[j]) j++;
if (j == m) return i;
j = 0;
}
i++;
}
return -1;
}
};