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

      

     

  • 相关阅读:
    Algs4-2.3.11快排遇与切分值相同时继续扫描是平方级
    使用kubeadm搭建Kubernetes集群
    kubernetes发布解释型语言应用的最佳实践
    docker化php项目发布方式
    linux服务器免密钥登录
    cp 递归复制时 复制实际文件而不是链接文件
    nginx配置http访问自动跳转到https
    nfs服务器
    nginx防止恶意域名解析
    如何建立自己的知识体系?(摘)
  • 原文地址:https://www.cnblogs.com/qianyuesheng/p/9069883.html
Copyright © 2011-2022 走看看