leeway00 / CodingTestPractice

0 stars 0 forks source link

Longest Substring Without Repeating Characters #7

Open leeway00 opened 2 years ago

leeway00 commented 2 years ago
    def lengthOfLongestSubstring(self, s: str) -> int:
        used = {}
        max_length = start = 0
        for ind, char in enumerate(s):
            # In case of resetting
            if char in used and start <= used[char]:
                start = used[char]+1
            # if not reset, update max_length
            else:
                max_length = max(max_length, ind-start+1)
            # update recently used index of char
            used[char] = ind
        return max_length
leeway00 commented 2 years ago

accept인데 비효율

        n = len(s)
        maximum = 0
        end = 0
        temp = []
        while end < n:
            if s[end] not in temp:
                temp.append(s[end])
                end +=1
            elif end == n-1:
                break
            else:
                maximum = max(maximum, len(temp))
                temp = temp[temp.index(s[end])+1:]
                while s[end] == s[end+1]:
                    end+=1
                    temp = []
                    if end == n-1:
                        break
        maximum = max(maximum, len(temp))
        return maximum
leeway00 commented 2 years ago
    def lengthOfLongestSubstring(self, s: str) -> int:
        charSet = set()
        l = 0
        res = 0

        for r in range(len(s)):
            while s[r] in charSet:
                charSet.remove(s[l])
                l += 1
            charSet.add(s[r])
            res = max(res, r - l + 1)
        return res