码迷,mamicode.com
首页 > 其他好文 > 详细

19.1.30 [LeetCode 28] Implement strStr()

时间:2019-01-30 13:11:30      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:click   str   hid   closed   ide   html   return   分享图片   就是   

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

标签:click   str   hid   closed   ide   html   return   分享图片   就是   

原文地址:https://www.cnblogs.com/yalphait/p/10337384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!