Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.
class Solution(object):
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
position_hash = {}
max_length = 0
start = 0
for char in s:
position_hash[char] = -1
for index, char in enumerate(s):
if position_hash[char] != -1:
while start <= position_hash[char]:
position_hash[s[start]] = -1
start += 1
if index - start + 1 > max_length:
max_length = index - start + 1
position_hash[char] = index
return max_length
O(n2) time and O(n) space

本文介绍了一种求解字符串中最长无重复字符子串长度的算法实现。通过使用哈希表记录每个字符的位置,该算法能在遍历过程中动态更新最长子串的长度。文章中的代码示例清晰地展示了如何高效地解决这一常见编程问题。
671

被折叠的 条评论
为什么被折叠?



