3. Longest Substring Without Repeating Characters Python3

Yelim Kim·2021년 10월 6일
0

Python Algorithm Interview

목록 보기
30/36
post-thumbnail

Problem

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 "abc", with the length of 3.

Example 2:

Input: s = "bbbbb"
Output: 1
Explanation: The answer is "b", with the length of 1.

Example 3:

Input: s = "pwwkew"
Output: 3
Explanation: The answer is "wke", with the length of 3.
Notice that the answer must be a substring, "pwke" is a subsequence and not a substring.

Example 4:

Input: s = ""
Output: 0

Constraints:

0 <= s.length <= 5 * 104
s consists of English letters, digits, symbols and spaces.

My code

class Solution:
    def lengthOfLongestSubstring(self, s):
        if s == '':
            return 0
        end = ''
        length = ''
        for c in s:
            if c not in end:
                end += c
            else:
                end = end.split(c)[1] + c
            if len(length) <= len(end):
                length = end
        return len(length)

Review

[실행 결과]
Runtime: 44 ms Memory Usage: 14.3 MB

[접근법]
저 길이를 int로 할까 스트링으로 할까 하다가 스트링으로 하기로 함
s안에 저장 글자에 있는 단어가 나오지 않을때까지 글자 저장하기
만약에 생기면 생긴 지점까지 끊고, 최대 길이와 길이 비교한다. 만약 최대 길이를 넘으면 저장한 글자를 최대 길이로 지정한다.

[느낀점]
같은 단어가 나오면 끊고 마지막 글자를 더해주는 부분을 참고하여 풀었다...!!

profile
뜬금없지만 세계여행이 꿈입니다.

0개의 댓글