面试题48:最长不含重复字符的子字符串

一、题目

    请从字符串中找出一个最长的不包含重复字符的子字符串,计算该最长子字符串的长度。假设字符串中只包含从'a'到'z'的字符。例如,在字符串“arabcacfr”中,最长的不含重复字符的子字符串是“acfr”,长度为4.

二、解法

    思路:利用动态规划算法,首先定义函数f(i)表示以第i个字符结尾的不包含重复字符的子字符串的最长长度。如果第i个字符之前没有出现过,那么f(i) = f(i-1) + 1, 如果第i个字符之前已经出现过,那情况就要复杂一点了,我们先计算第i个字符和它上次出现在字符串中的位置和距离,并记为d,接着分两种情形分析。第一种情形是d小于或者等于f(i-1),此时第i个字符上次出现在f(i-1)对应的最长子字符串之中,因此f(i) = d。第二种情形是d大于f(i-1),此时第i个字符上次出现在f(i-1)对应的最长子字符串之前,因此仍然有f(i) = f(i-1)+1。

2.1 方法一

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        curLength = 0
        maxLength = 0
        position = [-1 for _ in range(128)]
        
        for i in range(len(s)):
            prevIndex=position[ord(s[i]) - ord(' ')]
            if prevIndex==-1 or i-prevIndex>curLength:
                curLength += 1
            else:
                if curLength>maxLength:
                    maxLength = curLength
                curLength = i-prevIndex
            position[ord(s[i])-ord(' ')] = i
        if curLength > maxLength:
            maxLength = curLength
        return maxLength

2.2 方法二:使用hash表

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        curLength = 0
        maxLength = 0
        indexDict = {}
        for i in range(len(s)):
            if (s[i] not in indexDict) or (i-indexDict[s[i]]>curLength):
                curLength+=1
            else:
                if curLength>maxLength:
                    maxLength=curLength
                curLength = i-indexDict[s[i]]
            indexDict[s[i]] = i
        if curLength>maxLength:
            maxLength = curLength
        return maxLength

猜你喜欢

转载自blog.csdn.net/sinat_36161667/article/details/81037321