Skip to content

Commit 103d406

Browse files
author
tonardo2015
committed
update code to meet python naming and add test
1 parent 8a40e9b commit 103d406

File tree

5 files changed

+104
-137
lines changed

5 files changed

+104
-137
lines changed

python/001_Two_Sum.py

Lines changed: 0 additions & 66 deletions
This file was deleted.

python/003_Longest_Substring_Without_Repeating_Characters.py

Lines changed: 0 additions & 71 deletions
This file was deleted.

python/longest_substring.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution(object):
2+
'''
3+
leetcode 3
4+
:type s: str
5+
:rtype maxLength: int
6+
'''
7+
def lengthOfLongestSubstring(self, s):
8+
slideWindow = set()
9+
left, maxLength = 0, 0
10+
for right in range(len(s)):
11+
while s[right] in slideWindow:
12+
slideWindow.remove(s[left])
13+
left += 1
14+
slideWindow.add(s[right])
15+
maxLength = max(maxLength, right - left + 1)
16+
return maxLength
17+
18+
'''
19+
Why choose set() as data structure to store the slide window?
20+
It is because we need to tell if a character is in the slide window quickly.
21+
From Time Complexity perspective, it is much better. With list to tell if an element is in the slide window or to remove an element from the slide window, the Time Complexity is O(n); while using set, it is O(1). Overall Time Complexity comparison between List vs Set is O(n*n) vs O(n)
22+
23+
If using dict, there is additional Space occupancy as there is no need to save the Character to Index mapping.
24+
'''

python/test_longest_substring.py

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import pytest
2+
import sys
3+
import os
4+
5+
test_dir = os.path.dirname(os.path.abspath(__file__))
6+
if test_dir not in sys.path:
7+
sys.path.append(test_dir)
8+
9+
from longest_substring import Solution
10+
11+
@pytest.fixture(scope="function")
12+
def solution():
13+
return Solution()
14+
15+
test_cases = [
16+
# 常规场景(4个)
17+
("abcdef", 6, "无重复字符(全唯一):set持续add,无remove"),
18+
("abcabcbb", 3, "部分重复(中间重复):重复时remove左侧字符,窗口重置"),
19+
("bbbbb", 1, "连续重复(末尾重复):每次right移动都触发remove"),
20+
("pwwkew", 3, "重复字符间隔出现:窗口从'pw'→'wke'"),
21+
# 边界条件(4个)
22+
("", 0, "空字符串:set初始为空,无循环执行"),
23+
("a", 1, "单字符字符串:仅一次add,窗口长度1"),
24+
("aa", 1, "双字符重复:第二次循环触发remove,窗口重置为1"),
25+
("ab", 2, "双字符不重复:无remove,窗口长度递增至2"),
26+
# 特殊场景(4个)
27+
("a b c", 3, "包含空格字符:空格作为独立字符,set正常判重"),
28+
("a1b2!c", 6, "包含数字和符号:混合字符无重复,返回全长"),
29+
("abcde"*200 + "fghij", 10, "长字符串(1005字符):每5个重复,最长子串10"),
30+
("dvdf", 3, "重复字符在窗口中间:窗口从'dv'→'vdf'")
31+
]
32+
33+
@pytest.mark.parametrize("s, expected, case_desc", test_cases)
34+
def test_length_of_longest_substring(solution, s, expected, case_desc):
35+
"""
36+
测试lengthOfLongestSubstring函数的全场景功能
37+
:param solution: Fixture提供的Solution实例
38+
:param s: 输入字符串
39+
:param expected: 预期最长子串长度
40+
:param case_desc: 测试场景描述(用于失败时定位问题)
41+
"""
42+
43+
try:
44+
decoded_desc = codecs.decode(case_desc, 'unicode-escape')
45+
except Exception as e:
46+
decoded_desc = case_desc
47+
print(f"中文解码警告:{e},将使用原始描述:{case_desc}")
48+
49+
result = solution.lengthOfLongestSubstring(s)
50+
# 断言结果是否符合预期(失败时显示场景描述)
51+
assert result == expected, \
52+
f"测试失败:{decoded_desc}\n输入s:{s[:20]}...(总长{len(s)}\n预期结果:{expected}\n实际结果:{result}"
53+
54+
print(f"✓ 用例通过:{decoded_desc}(输入长度:{len(s)})")

python/two_sum.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution(object):
2+
'''
3+
leetcode 1
4+
:type nums: list[int]
5+
:type target: int
6+
:rtype res: [int]
7+
'''
8+
def twoSum(self, nums, target):
9+
# two point
10+
nums_index = [(v, index) for index, v in enumerate(nums)]
11+
nums_index.sort()
12+
begin, end = 0, len(nums) - 1
13+
while begin < end:
14+
curr = nums_index[begin][0] + nums_index[end][0]
15+
if curr == target:
16+
return [nums_index[begin][1], nums_index[end][1]]
17+
elif curr < target:
18+
begin += 1
19+
else:
20+
end -= 1
21+
22+
23+
if __name__ == '__main__':
24+
# begin
25+
s = Solution()
26+
print(s.twoSum([3, 2, 4], 6))

0 commit comments

Comments
 (0)