leetcode: 3. Longest Substring Without Repeating Characters(Python)

题目描述:

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

Examples:

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.

题目大意:

给定一个字符串,从中求出不含重复字符最长子串长度。例如,'abcabcbb'  的不含重复字符的最长子串为 'abc',其长度是3。

题目分析:

此题目可以使用滑动窗口法来做,现在介绍另外一种方法。

(1)、用变量maxlen、start、index, 分别记录最长不重复的子串、当前子串的开始位置、当前字符的位置。

(2)、store = {}, 用来每一个字符最新的位置

(3)、从左向右滑动每一个字符,如果当前字符已经存在store且当前子串的开始位置start <= 当前字符的位置,说明出现了重复字符,则更新子串的开始位置。然后更新store、maxlen直到结束。

Python实现(时间复杂度:O(n),空间复杂度:O(n)):

# @Time   :2018/6/18
# @Author :LiuYinxing


class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        store, maxlen, start, idx = {}, 0, 0, 0         # 初始化 store, 子串的长度, 开始位置, 当前字符位置
        for idx, char in enumerate(s, 1):               # 依次向右,判断 计算
            if char in store and start <= store[char]:  # 出现重复字符串,更新子串的开始位置
                start = store[char]
            store[char] = idx                  # 更新 store
            maxlen = max(maxlen, idx - start)  # 更新 maxlen
        return maxlen or idx                  # 考虑字符串长度为0的情况


if __name__ == '__main__':
    solu = Solution()
    s = 'abcabcbb'
    print(solu.lengthOfLongestSubstring(s))
欢迎指正哦^_^

猜你喜欢

转载自blog.csdn.net/xx_123_1_rj/article/details/80722941
今日推荐