-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimplement-strstr.html
More file actions
78 lines (70 loc) · 2.41 KB
/
Copy pathimplement-strstr.html
File metadata and controls
78 lines (70 loc) · 2.41 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
<head><title>implement strstr</title>
<link rel="stylesheet" href="/style.css">
</head>
<body>
<link rel="stylesheet" href="/third-party/highlight/solarized-dark.css">
<script src="/third-party/highlight/highlight.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<h2>Yanzhan's solution for "implement strstr"</h2>
<ul>
<li>Hi, I'm Yanzhan. For more algothmic problems, visit my Youtube Channel <a href="https://www.youtube.com/channel/UCDkz-__gl3frqLexukpG0DA?view_as=subscriber" target=_blank>[Yanzhan Yang's Youtube Channel]</a> or my Twitter Account <a href="https://twitter.com/YangYanzhan" target=_blank>[Yanzhan Yang's Twitter]</a> or my GitHub HomePage <a href="https://github.com/yangyanzhan/code-camp" target=_blank>[Yanzhan Yang's GitHub Project]</a> .</li>
<li>It's fascinating to solve algothmic problems, follow Yanzhan to learn more!</li>
</ul>
<div>
</div>
<div>
</div>
<div>
</div>
<h3>
solution:
</h3>
<pre class="yanzhan-hidden"><code class="c++">class Solution {
int base1 = 13;
int base2 = 99999997;
public:
int strStr(string haystack, string needle) {
int n = needle.size();
int m = haystack.size();
if (m < n) {
return -1;
}
string curr = haystack.substr(0, n);
int h1 = hash(needle);
int h2 = hash(curr);
if (h1 == h2) {
return 0;
}
for (int i = n; i < m; i++) {
int front = char_hash(haystack[i - n], n);
h2 -= front;
h2 = (base1 * h2 + haystack[i]) % base2;
h2 = (h2 + base2) % base2;
if (h1 == h2) {
return i - n + 1;
}
}
return -1;
}
int hash(string item) {
long long sum = 0;
for (int i = 0; i < item.size(); i++) {
sum = (base1 * sum + item[i]) % base2;
}
return sum;
}
int char_hash(char ch, int repeats) {
long long total = ch;
for (int i = 1; i < repeats; i++) {
total = (base1 * total) % base2;
}
return total;
}
};
</code></pre>
<ul class="yanzhan-hidden">
<li><a href="/index.html" target=_blank>[Go Back To HomePage]</a></li>
<li><a href="/leetcode" target=_blank>[Go Back To Solution List Page]</a></li>
</ul>
<script src="/main.js"></script>
</body>