출처: https://astrocosmos.tistory.com/202 [ASTROCOSMOS] [LeetCode] #2 Longest Substring Without Repeating Characters
본문 바로가기
Algorithm

[LeetCode] #2 Longest Substring Without Repeating Characters

by 헤지월드 2021. 7. 31.
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        dic, res, start, = {}, 0, 0        
        for i, ch in enumerate(s):  # enumerate 함수를 이용해 각 값에 인덱스를 부여해준다.
            if ch in dic:                    # 현재 for문에서 판정되고 있는 문자와 동일한 문자가 딕셔너리에 있을 경우 
                res = max(res, i-start)   # 딕셔너리 내 현재까지 문자 요소가 반복되지 않은 문자열의 최대 길이
                start = max(start, dic[ch]+1)   # 다음 순서로 판정할 문자의 인덱스
            dic[ch] = i                                        # 딕셔너리에 문자와 인덱스 추가
        return max(res, len(s)-start)            # 동일한 문자가 중복되지 않은 문자열 중 가장 긴 문자열의 길이 리턴

댓글