-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement_strstr.cc
More file actions
116 lines (105 loc) · 2.43 KB
/
implement_strstr.cc
File metadata and controls
116 lines (105 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
// Source: https://leetcode-cn.com/problems/implement-strstr
// Author: Shihao Liu
// Date: 2021-11-21
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Solution_1 {
public:
/**
* @brief 暴力求解
*
* 时间复杂度: O(m*n)
*
* 从haystack中找出needle出现的第一个位置. 不存在时返回-1. needle为空串时返回0.
*
* tip: 如果不事先保存两个串的长度到变量中, 而是在for循环判断里临时调用size(), 则
* 提交答案后, 最后一个测试用例将会"超出时间限制".
*/
int strStr(string haystack, string needle) {
if (needle == "") {
return 0;
}
int len1 = haystack.size(), len2 = needle.size();
int i, j;
for (i = 0; i + len2 <= len1; i++) {
for (j = 0; j < len2; j++) {
if (haystack[i + j] == needle[j]) {
continue;
} else {
break;
}
}
if (j == len2) {
return i;
}
}
return -1;
}
};
// AC
class Solution_2 {
private:
// 初始化: 依据模式串t生成next数组
// 要求: 模式串不为空
void kmp_init(const string& t, vector<int>& next) {
next[0] = -1; // 规定
int i = 0, j = -1;
int m = t.size();
while (i < m - 1) {
if (j == -1 || t[i] == t[j]) {
i++;
j++;
next[i] = j;
} else {
j = next[j];
}
}
}
public:
/**
* @brief KMP算法(背诵)
*
* 时间复杂度: O(n+m), n, m分别为主串和模式串的长度.
*
* KMP代码实现太难了, 搞了一整晚思路还是理不清.
* 把它当模板背下来吧...
* (注意: 数组下标从0开始)
*/
int strStr(string haystack, string needle) {
// 先处理模式串为空的情况
if (needle.empty()) {
return 0;
}
int n = haystack.size(), m = needle.size();
vector<int> next(m);
kmp_init(needle, next);
int i = 0, j = 0;
while(i < n && j < m) {
if (j == -1 || haystack[i] == needle[j]) {
i++;
j++;
} else {
j = next[j];
}
}
if (j == m) {
return i - m;
} else {
return -1;
}
}
};
int main() {
string h = "hello", n = "ll";
Solution_1 sol;
cout << sol.strStr(h, n) << endl;
h = "aaaaa"; n = "bba";
cout << sol.strStr(h, n) << endl;
h = ""; n = "";
cout << sol.strStr(h, n) << endl;
Solution_2 sol2;
h = "ababcababa"; n = "ababa";
cout << sol2.strStr(h, n) << endl;;
}