zoukankan      html  css  js  c++  java
  • [LeetCode]题解(python):003-Longest Substring Without Repeating Characters

     

    题目来源:

    https://leetcode.com/problems/longest-substring-without-repeating-characters/


    题意分析:

         题目是要求出最长的不重复子字符串的长度。比如字符串abcabcbb,得到的最长无重复子字符串就是abc,bca或者cab,那么它最长的不重复长度就是3.


    题目思路:

        首先,我们可以想到的方法就是每个字符为起点,找到对应的最长不重复子字符串长度,最后进行比较得到最长的不重复子字符串长度。这个方法的时间复杂度为(O(n^2))。如果用这个方法,那么很容易就会TLE。

        那么我们回想一下题目例子我们找无重复子字符串的过程。我们从第二个a开始找的时候,找到了倒数第二个b,发现b已经出现过了,这时候,我们再从第二个b开始找,那么得到的无重复子字符串必定比从a开始找要短,那么我们就不需要再从b开始找,而是从c开始找。也就是说,当我们发现这个字符在前面的无重复子字符串出现的位置后一位开始找。如此我们可以节省很多时间,并且我们只需要从头找一次就可以得到答案。时间复杂度为(O(nlogn)。


    代码(python):

    class Solution(object):
        def lengthOfLongestSubstring(self, s):
            """
            :type s: str
            :rtype: int
            """
            lls = 1
            if len(s) == 0:
                return 0
            if len(s) == 1:
                return 1
            i = 1
            curbegin = 0
            while i < len(s):
                cur = s.find(s[i],curbegin,i)
                if cur != -1:
                    lls = max(lls,i - curbegin)
                    curbegin = cur + 1
                i += 1
            if s.find(s[len(s) - 1],curbegin,len(s) - 1) == -1:
                return max(lls,len(s) - curbegin)
            return lls
    View Code

    PS:这里很容易忘记处理当最后一个字符再前面无重复子字符串里面的情况。


    转载请注明出处:http://www.cnblogs.com/chruny/

  • 相关阅读:
    Leetcode Substring with Concatenation of All Words
    Leetcode Divide Two Integers
    Leetcode Edit Distance
    Leetcode Longest Palindromic Substring
    Leetcode Longest Substring Without Repeating Characters
    Leetcode 4Sum
    Leetcode 3Sum Closest
    Leetcode 3Sum
    Leetcode Candy
    Leetcode jump Game II
  • 原文地址:https://www.cnblogs.com/chruny/p/4789098.html
Copyright © 2011-2022 走看看