zoukankan      html  css  js  c++  java
  • 3. Longest Substring Without Repeating Characters

    Description:

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

    给定字符串,求出最长的不重复的子串。

    Example:

    Given "abcabcbb", the answer is "abc", which the length is 3.
    
    Given "bbbbb", the answer is "b", with the length of 1.
    
    Given "pwwkew", 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, s):
            start = maxLength = 0  
            usedChar = {}
            
            for i in range(len(s)):
                if s[i] in usedChar and start <= usedChar[s[i]]:  # “并且”
                    start = usedChar[s[i]] + 1
                else:
                    maxLength = max(maxLength, i - start + 1)  # max的使用很巧妙
    
                usedChar[s[i]] = i # 将值填入
            return maxLength

      需要3个临时变量来查找最长子串:开始,最大长度,并使用字符。从一系列的字符开始,一次一个。如果当前字符是在usedchars map中,这将意味着我们已经看过并存储了相应的索引。如果它在那里,开始索引是<=那个索引,更新开始到最后看到重复的索引+ 1。这将把开始索引放在合适的位置。通过当前值的最后一次看到的副本。这让我们拥有了不包含重复的最长可能子串。如果不是在usedchars地图,我们可以计算出到目前为止看到的最长的子串。只需使用当前索引减去开始索引即可。如果值比最大长度长,将最大长度设置为它。最后,更新usedchars地图包含我们已经完成的当前值。@tapatio

    class Solution:
        """
            :type s: str
            :rtype: int
        """
        def lengthOfLongestSubstring(self, s):
            start = maxLength = 0
            usedChar = {}
         # 调用enumerate, 思想类似 for index,char in enumerate(s): if char in usedChar and start <= usedChar[char]: start = usedChar[char] + 1 else: maxLength = max(maxLength, index - start + 1) usedChar[char] = index return maxLength

      

     

  • 相关阅读:
    Spring多数据源动态切换
    IntelliJ Idea使用代码格式化,Tab制表符进行缩进
    idea 快捷键
    final关键字的功能概述
    IntelliJ Idea 常用快捷键列表
    Log4j.properties配置详解
    IDEA添加try catch快捷键
    使用 JMeter 进行压力测试
    idea 复制当前行到下一行快捷键
    js父窗口opener与parent
  • 原文地址:https://www.cnblogs.com/qianyuesheng/p/9069883.html
Copyright © 2011-2022 走看看