LeetCode-3:Longest Substring Without Repeating Characters (最长无重复字符的子串)

题目:

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

例子:

Given "abcabcbb", the answer is "abc", which the length is 3.

Given "bbbbb", the answer is "b", with the length of 1.

Given "pwwkew", 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.

问题解析:

给定一个字符串,从中找出不含重复字符的最长子串的长度。

解题思路:

算法:DP(动态规划)
数据结构:Vector

  • 假设L[i] = s[start … i],表示最长的子字符串,其中没有重复的元素,我们以Vector作为hashmap保存< 字符,索引>;
  • 然后访问s[i + 1]:
    • 1)如果s[i + 1]没有出现在散列表dict中,我们可以将s[i + 1]添加到散列表中,则有L[i + 1] = s[start … i + 1];
    • 2)如果s[i + 1]存在于dict中,并且dict中对应的索引是k;则令start = max(start,k),则L[i + 1] = s[start … i + 1],记录此时的最大长度;
  • 整个问题就是围绕不加入重复元素而展开的。
  • 时间复杂度:O(n)
    代码(python)
class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        start = maxLength = 0
        usedChar = {}

        for i in range(len(s)):
            if s[i] in usedChar and start <= usedChar[s[i]]:
                start = usedChar[s[i]] + 1
            else:
                maxLength = max(maxLength, i - start + 1)

            usedChar[s[i]] = i

        return maxLength

算法相关

动态规划:https://www.zhihu.com/question/23995189
动态规划:https://blog.csdn.net/cr496352127/article/details/77934132?locationNum=10&fps=1

猜你喜欢

转载自blog.csdn.net/qq_36653505/article/details/81088820