관리 메뉴

솜씨좋은장씨

[leetCode] 3. Longest Substring Without Repeating Characters (Python) 본문

Programming/코딩 1일 1문제

[leetCode] 3. Longest Substring Without Repeating Characters (Python)

솜씨좋은장씨 2020. 5. 11. 17:05
728x90
반응형

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

 

Example 1:

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

Example 2:

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

Example 3:

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

 

Solution

class Solution:
    def lengthOfLongestSubstring(self, my_str: str) -> int:
        answer = 0
        
        substrings = []
        
        my_str_list = list(my_str)
        
        set_list = set(my_str_list)
        
        if len(set_list) == 0:
            answer = 0
        elif len(set_list) == 1:
            answer = 1
        else:
            for i in range(len(my_str_list)):
                sub = []
                for j in range(i, len(my_str_list)):
                    if my_str_list[j] in sub:
                        substring = ''.join(sub)
                        substrings.append(len(substring))
                        break
                    sub.append(my_str_list[j])
                    
                    if j == len(my_str_list) - 1:
                        substring = ''.join(sub)
                        substrings.append(len(substring))

            answer = max(substrings)
                            
        return answer

 

 

SOMJANG/CODINGTEST_PRACTICE

1일 1문제 since 2020.02.07. Contribute to SOMJANG/CODINGTEST_PRACTICE development by creating an account on GitHub.

github.com

 

Comments