zoukankan      html  css  js  c++  java
  • 【leetcode】Longest Substring Without Repeating Characters

    题目描述:

    Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

    解题思路:

    暴力方法不谈。学到了一种O(n)的方法,思想也是两个指针(我自己开始的AC代码考虑的是不匹配的回退值,不仅麻烦而且通用性还不够好)。首先我们用left和right分别表示满足题目的序列的两端下标,那么我们可以想到,首先在该值不重复的时候不断移动right指针,当遇到重复时我们则要比较是否满足最长,另外要移动left找到最佳的重新开始长度,这个长度就是使得新加入的right不是重复的。

    class Solution:
        # @return an integer
        def lengthOfLongestSubstring(self, s):
            left =0 
            right = 0
            res = 0
            lis = [] 
            l = len(s)
            while right < l:
                if s[right] in lis:
                    if res < right - left:
                        res = right - left
                    while s[left] != s[right]:
                        lis.remove(s[left])
                        left += 1
                    left += 1
                else:
                    lis.append(s[right])
                right += 1
            if res < right - left:
                res = right - left
            return res
  • 相关阅读:
    Educational Codeforces Round 23E
    Educational Codeforces Round 23D
    Codeforces Round #461 (Div. 2)
    HYSBZ
    HDU
    HYSBZ
    HYSBZ
    SPOJ
    点击搜索条件提交form表单
    HTML颜色获取工具,colorpicker
  • 原文地址:https://www.cnblogs.com/MrLJC/p/4242177.html
Copyright © 2011-2022 走看看