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) |
Solution2:
for循环, j作为needle的下标, i作为判断的头指针, i+j是haystack的下标,
- 1, 若两个指针指向的字符不同, 推出内层循环;
- 2, 如果j能够在上述条件下, 到达哨兵位置, 表明完全匹配;
- 3, 如果i+j到了haystack的哨兵位置, 扫描结束, 未找到;
// Time:O(n*m), Space:O(1) |
根据这个思路, 对Solution1进行简化,
- 用达到哨兵位置取代对ok变量的操作;
- 用i+j取代新增的k变量;
- i的范围在n-m之内.
// 第一个版本的简化版本 |