算法--Longest Substring Without Repeating Characters

问题:最大不重复连续子串的长度

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

Example :Input: "pwwkew" Output: 3 Explanation: 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.

以s=“habcdeabcd”为例,利用动态规划思想,令f(i)表示以s[i]结尾的最大不重复子串长度大小。考虑f(i)与f(i-1)关系:

当i==0时,即字符串第一个 有f(0)=1

当i>1时,查询s[i]在s[0:i-1]中是否出现过:

  若没有出现过,显然有:

  f(i) = f(i-1)+1

  若出现过,则考虑上一次出现的位置plast ,与上一次之间的距离d = i - plast,

      若d>f(i-1),有 f(i) = f(i-1)+1

      若d<=f(i-1),有 f(i) = d

为例便于查询字符上一次出现的位置,利用一个大小128数组来保存字符与出现位置的索引,可以实现O(1)复杂度查询

def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """       
        if s==None or s=='':
            return 0
        if s.isspace():
            return 1
        pos = [-1 for i in range(128)]
        dp = [0 for i in range(len(s))]
        dp[0] = 1
        pos[ord(s[0])-ord('a')] = 0
        for i in range(1, len(s)):
            #该字符上一次出现的位置
            p = pos[ord(s[i])-ord('a')]
            #如果没有出现
            if p==-1:
                dp[i] = dp[i-1] + 1
            #如果出现过,但是距离大于dp[i-1]
            elif i-p>dp[i-1]:
                dp[i] = dp[i-1] + 1
            #出现过,距离小于dp[i-1]
            else:
                dp[i] = i-p
            pos[ord(s[i])-ord('a')] = i
        #print (dp)
        #print (pos)
        return max(dp)

最后返回dp数组中最大值即可。

python中  字符与ASC的转换  ord()  str()

pos数组索引映射为字符ASC码,值存储为该字符上一次出现的位置,初始化为-1

猜你喜欢

转载自blog.csdn.net/u014106644/article/details/84063627