19.1.30 [LeetCode 28] Implement strStr()

Posted TobicYAL

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了19.1.30 [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().

题意

实现找子串函数

题解

技术分享图片
 1 class Solution {
 2 public:
 3     int* findNext(string P) {
 4         int i, k;
 5         int m = P.length();
 6         int *next = new int[m];
 7         next[0] = -1;
 8         i = 0; k = -1;
 9         while (i < m - 1) {
10             while (k >= 0 && P[k] != P[i])
11                 k = next[k];
12             i++, k++;
13             if (P[k] == P[i])
14                 next[i] = next[k];
15             else next[i] = k;
16         }
17         return next;
18     }
19     int strStr(string haystack, string needle) {
20         if (needle == "")return 0;
21         int *next = findNext(needle);
22         int p1 = 0, p2 = 0;
23         int l1 = haystack.length(), l2 = needle.length();
24         while (p1 < l1&&p2 < l2) {
25             if (haystack[p1] == needle[p2]) {
26                 p1++, p2++;
27                 continue;
28             }
29             p2 = next[p2];
30             if (p2 == -1) {
31                 p1++; p2 = 0;
32             }
33         }
34         if (p2 != l2)return -1;
35         return p1 - l2;
36     }
37 };
View Code

说到找子串就是kmp啦

以上是关于19.1.30 [LeetCode 28] Implement strStr()的主要内容,如果未能解决你的问题,请参考以下文章

19.1.30 [LeetCode 24] Reverse Nodes in k-Group

win7下qt error: undefined reference to `_imp__getnameinfo@28'解决

LeetCode刷题

Leetcode 28 - 实现 strStr():问题

LeetCode 28 实现 strStr()

Leetcode题解(28)