tech-cow/leetcode

3. Longest Substring Without Repeating Characters

tech-cow opened this issue · 1 comments

globalSet这块看了下答案,没完全写对,再刷一次

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        globalMax = -float('inf')
        globalSet = set()
        j = 0
        
        for i in range(len(s)):
            while j < len(s) and s[j] not in globalSet:
                globalSet.add(s[j])
                globalMax = max(globalMax, len(globalSet))
                j += 1
            globalSet.remove(s[i])
        
        return globalMax if globalMax != -float('inf') else 0
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        maxLen = 0
        visited = set()
        
        n = len(s)
        i, j = 0, 0

        while i < n and j < n:
            if s[j] not in visited:
                visited.add(s[j])
                maxLen = max(maxLen, j - i + 1)
                j += 1
            else:
                visited.remove(s[i])
                i += 1
        return maxLen