Catalogue
is Substring
28. Implement strStr()
1 | class Solution(object): |
Solution2. KMP
- Time : O(m + n)
- know the basic idea of KMP and can walk through some test cases
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
27class Solution(object):
def getNext(self, pattern):
m = len(pattern)
next = [0] * m
k = 0
for i in xrange(1, m):
while k > 0 and pattern[k] != pattern[i]:
k = next[k-1]
if pattern[k] == pattern[i]:
k += 1
next[i] = k
return next
def strStr(self, haystack, needle):
if not needle:
return 0
next = self.getNext(needle)
n = len(haystack)
p = 0
for i in xrange(n):
while p > 0 and needle[p] != haystack[i]:
p = next[p-1]
if needle[p] == haystack[i]:
p += 1
if p == len(needle):
return i-len(needle)+1
return -1
Solution3. Robin-Karp
- Time : O(m+n)
- Principle: if we can hash the short string to a hashed value (e.g. integer, which is unique). Then we can just compare each substring of s1’s hashed value and compare it with s2’s hash value.
- Assumption: only lower case letter (base = 26 a–z)
- Each time you slide the window, add right, delete left and times 26 in the middle!!!
Sliding Window
A string has $n^2$ substrings! These type of question ask you to find a subtring meet some certain condition!
- Slinding Window + Hash Table!!!
3. Longest Substring Without Repeating
- When to move the right pointer and when to move the left pointer
- use hashset
1 | class Solution(object): |
159. Longest Substring with At Most Two Distinct Characters
1 | class Solution(object): |
340. Longest Substring with At Most K Distinct Characters
1 | class Solution(object): |
76. Minimum Window Substring
- it will be easy to let right pointer be the iteration pointer
- cnt is the flag to show whether it satisfies the condition
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
26class Solution(object):
def minWindow(self, s, t):
tmap = {}
for c in t:
tmap[c] = tmap.get(c, 0) + 1
cnt = len(t)
start = 0
res, ret = len(s)+1, ""
for i in xrange(len(s)):
if s[i] in tmap:
tmap[s[i]] -= 1
if tmap[s[i]] >= 0:
cnt -= 1
while cnt == 0:
win = i-start+1
if win < res:
res = win
ret = s[start:i+1]
if s[start] in tmap:
if tmap[s[start]] >= 0:
cnt += 1
tmap[s[start]] += 1
start += 1
return ret
438. Find All Anagrams in a String
1 | class Solution(object): |