Description
给定一个字符串,请找出其中无重复字符的最长子字符串。
Example
输入: “abcabcbb”
输出: 3
解释: 最长子串是 “abc”.
思路
使用同相双指针,用一个set记录unique字符,每当有重复字符记录最新的最长长度
解
class Solution:
"""
@param s: a string
@return: an integer
"""
def lengthOfLongestSubstring(self, s):
# write your code here
unique = set([])
j = 0
length = len(s)
longest = 0
for i in range(length):
while j < length and s[j] not in unique:
unique.add(s[j]
j += 1
longest = max(longest, j - i)
unique.remove(s[i])
return longest
分析
时间复杂度 O(n)
空间复杂度 O(1)