Skip to content

Commit 508b991

Browse files
Hai Hoang Dangdanghai
authored andcommitted
Fix longest_non_repeat by sliding windown method (keon#390)
Fixes keon#388
1 parent 3879607 commit 508b991

File tree

2 files changed

+22
-12
lines changed

2 files changed

+22
-12
lines changed

algorithms/arrays/longest_non_repeat.py

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,19 +12,17 @@
1212

1313
def longest_non_repeat_v1(string):
1414
"""
15-
Finds the length of the longest substring
16-
without repeating characters.
15+
Apply slide windown.
1716
"""
18-
if string is None:
19-
return 0
20-
temp = []
21-
max_len = 0
22-
for i in string:
23-
if i in temp:
24-
temp = []
25-
temp.append(i)
26-
max_len = max(max_len, len(temp))
27-
return max_len
17+
dict = {}
18+
max_length = 0
19+
j = 0
20+
for i in range(len(string)):
21+
if string[i] in dict:
22+
j = max(dict[string[i]], j)
23+
dict[string[i]] = i + 1
24+
max_length = max(max_length, i - j + 1)
25+
return max_length
2826

2927

3028
def longest_non_repeat_v2(string):

tests/test_array.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -147,6 +147,12 @@ def test_longest_non_repeat_v1(self):
147147
string = "pwwkew"
148148
self.assertEqual(longest_non_repeat_v1(string), 3)
149149

150+
string = "dvdf"
151+
self.assertEqual(longest_non_repeat_v1(string), 3)
152+
153+
string = "asjrgapa"
154+
self.assertEqual(longest_non_repeat_v1(string), 6)
155+
150156
def test_longest_non_repeat_v2(self):
151157

152158
string = "abcabcbb"
@@ -158,6 +164,12 @@ def test_longest_non_repeat_v2(self):
158164
string = "pwwkew"
159165
self.assertEqual(longest_non_repeat_v2(string), 3)
160166

167+
string = "dvdf"
168+
self.assertEqual(longest_non_repeat_v2(string), 3)
169+
170+
string = "asjrgapa"
171+
self.assertEqual(longest_non_repeat_v2(string), 6)
172+
161173

162174
class TestMaxOnesIndex(unittest.TestCase):
163175

0 commit comments

Comments
 (0)