[3] Longest Substring Without Repeating Characters | Leetcode Medium


🔎 問題の説明


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.
せいげんじょうけん
  • 0 <= s.length <= 5 * 10410^4104
  • s consists of English letters, digits, symbols and spaces.
  • 結論は,アルファベットを繰り返さない最大文字列長を求める問題である.
    制限条項のため、暴力を振るうとタイムアウトする可能性があります.これはちょっと難しい問題です.

    🧊 Pythonコード

    class Solution:
        def lengthOfLongestSubstring(self, s: str) -> int:
            save = []
            max_len = 0
        
            for x in s:
                if x in save:
                    save = save[save.index(x)+1:]
                save.append(x)    
                max_len = max(max_len, len(save))
            
            return max_len
    各文字をチェックするときに、前の文字であれば、文字列内でその位置に切り取られる前に、そうでなければ文字列の後ろに追加します.各ステップにmax lenを保存します.