문제

 

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

 

Longest Substring Without Repeating Characters - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

Given a string s, find the length of the longest substring without repeating characters.

1. 문자열 s가 주어지고, 연속으로 다른 알파벳이 나오는 가장 긴 문자열을 찾아라.

Input Output
s = "abcabcbb" 3
Explanation: The answer is "abc", with the length of 3.

 

문제풀이 코드

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        if len(s) <= 0:
            return 0
        result = [0 for _ in range(len(s))]
        idx = 0
        s = list(s)
        while s:
            char = s.pop(0)
            lst = [char]
            for i in range(len(s)):
                if char == s[i] or s[i] in lst:
                    break
                lst.append(s[i])
            result[idx] = len(lst)
            idx += 1
        return max(result)

1. 문자열의 각 문자별로 최대 길이를 담는 리스트를 생성

2. 문자열 s의 첫번째 문자를 pop한다

3. 뽑혀나온 문자를 문자열s의 요소들을 하나씩 비교

4. char과 s[i]가 같거나 s[i]가 lst에 들어있다면(중복되어있다) for루프를 빠져나온다

5. 둘다 아니라면 lst에 s[i]를 삽입

6. for루프가 정상적으로 종료되었을 때 lst는 char로 시작하는 연속된 문자열이 들어가있다

7. lst의 길이를 result에 넣어준다

8. 문자열의 모든 문자별로 가질 수 있는 최대값이 result에 들어있으므로 max값을 return

+ Recent posts