Skip to content

Commit cffaa16

Browse files
authored
Create maximum-number-of-occurrences-of-a-substring.py
1 parent dfa39ee commit cffaa16

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# Time: O(n)
2+
# Space: O(n)
3+
4+
import collections
5+
6+
7+
# rolling hash (Rabin-Karp Algorithm)
8+
class Solution(object):
9+
def maxFreq(self, s, maxLetters, minSize, maxSize):
10+
"""
11+
:type s: str
12+
:type maxLetters: int
13+
:type minSize: int
14+
:type maxSize: int
15+
:rtype: int
16+
"""
17+
M, p = 10**9+7, 113
18+
power, rolling_hash = pow(p, minSize-1, M), 0
19+
20+
left = 0
21+
lookup, count = collections.defaultdict(int), collections.defaultdict(int)
22+
for right in xrange(len(s)):
23+
count[s[right]] += 1
24+
if right-left+1 > minSize:
25+
count[s[left]] -= 1
26+
rolling_hash = (rolling_hash - ord(s[left])*power) % M
27+
if count[s[left]] == 0:
28+
count.pop(s[left])
29+
left += 1
30+
rolling_hash = (rolling_hash*p + ord(s[right])) % M
31+
if right-left+1 == minSize and len(count) <= maxLetters:
32+
lookup[rolling_hash] += 1
33+
return max(lookup.values() or [0])
34+
35+
36+
# Time: O(m * n), m = 26
37+
# Space: O(m * n)
38+
class Solution2(object):
39+
def maxFreq(self, s, maxLetters, minSize, maxSize):
40+
"""
41+
:type s: str
42+
:type maxLetters: int
43+
:type minSize: int
44+
:type maxSize: int
45+
:rtype: int
46+
"""
47+
lookup = {}
48+
for right in xrange(minSize-1, len(s)):
49+
word = s[right-minSize+1:right+1]
50+
if word in lookup:
51+
lookup[word] += 1
52+
elif len(collections.Counter(word)) <= maxLetters:
53+
lookup[word] = 1
54+
return max(lookup.values() or [0])

0 commit comments

Comments
 (0)