ZhangZhihui's Blog  

Given a string s, find the length of the longest  without duplicate 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.

 

Constraints:

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

 

My Solution:

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        
        n = len(s)
        left = 0
        max_substr = ''
        max_length = 0

        for right in range(n):
            try:
                new_left = max_substr.index(s[right])
                left = new_left + 1
                max_substr = max_substr[left:] + s[right]
            except ValueError:
                max_substr += s[right]
                max_length = max(max_length, len(max_substr))

        return max_length

 

 

posted on 2025-03-15 11:48  ZhangZhihuiAAA  阅读(21)  评论(0)    收藏  举报