본문 바로가기

PS/릿코드

[릿코드 3] Longest Substring Without Repeating Characters (파이썬/python)

728x90

https://leetcode.com/problems/longest-substring-without-repeating-characters/

 

Longest Substring Without Repeating Characters - LeetCode

Can you solve this real interview question? Longest Substring Without Repeating Characters - Given a string s, find the length of the longest substring without repeating characters.   Example 1: Input: s = "abcabcbb" Output: 3 Explanation: The answer is "

leetcode.com

 

 

딕셔너리에 문자열의 키와 인덱스를 저장해놓고

겹치는 문자 있을경우 그에따라 값을 조정하면서 최대 길이를 구해주었다.

 

 

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        answer = 0
        # key = char / value = index
        char_dic = {}
        left_idx = 0

        for right_idx, char in enumerate(s):
            if char not in char_dic:
                answer = max(answer, (right_idx - left_idx + 1))
            else:
                if char_dic[char] < left_idx:
                    answer = max(answer, (right_idx - left_idx + 1))
                else:
                    left_idx = char_dic[char] + 1

            char_dic[char] = right_idx

        return answer
728x90