- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3.py
More file actions
Latest commit
56 lines (42 loc) · 1.46 KB
/
Copy path3.py
File metadata and controls
56 lines (42 loc) · 1.46 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
importunittest
# Name: Longest Substring Without Repeating Characters
# Link: https://leetcode.com/problems/longest-substring-without-repeating-characters/
# Method: 2 pointers, sliding window and a set
# Time: O(n)
# Space: O(n)
# Difficulty: Medium
classSolution:
deflengthOfLongestSubstring(self, s: str) ->int:
ifnots:
return0
len_max=1
elem_seen=set()
start=0
fori, ltrinenumerate(s):
ifltrinelem_seen:
len_max=max(i-start, len_max)
whilestart<iandltrinelem_seen:
elem_seen.remove(s[start])
start+=1
elem_seen.add(ltr)
len_max=max(len(s) -start, len_max)
returnlen_max
classTestLongestNoRepeats(unittest.TestCase):
defsetUp(self):
self.sol=Solution()
deftest_lc_1(self):
res=self.sol.lengthOfLongestSubstring("abcabcbb")
self.assertEqual(res, 3)
deftest_lc_2(self):
res=self.sol.lengthOfLongestSubstring("bbbb")
self.assertEqual(res, 1)
deftest_lc_3(self):
res=self.sol.lengthOfLongestSubstring("pwwkew")
self.assertEqual(res, 3)
deftest_re_appear(self):
res=self.sol.lengthOfLongestSubstring("abcdbefzghij")
self.assertEqual(res, 10)
deftest_all_uniq(self):
res=self.sol.lengthOfLongestSubstring("abcd")
self.assertEqual(res, 4)
unittest.main()