美文网首页
python遇上LeetCode:无重复字符的最长子串

python遇上LeetCode:无重复字符的最长子串

作者: DATA_KENGOU | 来源:发表于2020-02-11 12:11 被阅读0次

    题目来源

    注意点:

    1. 空值的异常处理
    2. 滑动窗口的使用
    3. 利用字典(hash)来提高速度

    源码如下:

    class Solution:
        def lengthOfLongestSubstring(self, s: str) -> int:
            s_dict = dict()
            i, j = 0, 0 
            max_rec = 0
            while j < len(s):
                if s[j] in s_dict: #字典用于记录滑动窗口的左侧;
                # 即发现重复字母后,快速将i放到上一个重复字母的右侧
                    i = max(s_dict[s[j]]+1, i)
                s_dict[s[j]] = j
                max_rec = max(max_rec, j - i + 1)
                j += 1
            return max_rec
    

    相关文章

      网友评论

          本文标题:python遇上LeetCode:无重复字符的最长子串

          本文链接:https://www.haomeiwen.com/subject/lhxzxhtx.html