Skip to content

Commit fd8e3c4

Browse files
authored
Update maximum-number-of-non-overlapping-substrings.py
1 parent f9d1054 commit fd8e3c4

File tree

1 file changed

+11
-7
lines changed

1 file changed

+11
-7
lines changed

Python/maximum-number-of-non-overlapping-substrings.py

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,15 @@ def maxNumOfSubstrings(self, s):
4343
:type s: str
4444
:rtype: List[str]
4545
"""
46+
def find_right_from_left(s, first, last, left):
47+
right, i = last[ord(s[left])-ord('a')], left
48+
while i <= right:
49+
if first[ord(s[i])-ord('a')] < left:
50+
return -1
51+
right = max(right, last[ord(s[i])-ord('a')])
52+
i += 1
53+
return right
54+
4655
first, last = [float("inf")]*26, [float("-inf")]*26
4756
for i, c in enumerate(s):
4857
first[ord(c)-ord('a')] = min(first[ord(c)-ord('a')], i)
@@ -51,13 +60,8 @@ def maxNumOfSubstrings(self, s):
5160
for c in xrange(len(first)):
5261
if first[c] == float("inf"):
5362
continue
54-
left, right = first[c], last[c]
55-
i = left
56-
while i <= right:
57-
left = min(left, first[ord(s[i])-ord('a')])
58-
right = max(right, last[ord(s[i])-ord('a')])
59-
i += 1
60-
if left == first[c]:
63+
left, right = first[c], find_right_from_left(s, first, last, first[c])
64+
if right != -1:
6165
intervals.append((right, left))
6266
intervals.sort() # Time: O(26log26)
6367
result, prev = [], -1

0 commit comments

Comments
 (0)