Leetcode 3: Longest Substring Wi

作者: Zentopia | 来源:发表于2017-11-01 22:27 被阅读24次

求解最长不重复子串 Python 3 实现:

源代码已上传 Github,持续更新。

"""
3. Longest Substring Without Repeating Characters

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.
"""

class Solution:
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """

        max_len = 0
        left = 0
        right = 0
        dic = {}
        sub_len = 0
        while right < len(s):
            right_value = s[right]
            if right_value in dic and dic[right_value] >= left:
                sub_len = right - left
                max_len = max(max_len, sub_len)
                left = dic[right_value] + 1
                dic[right_value]=right
                right += 1
            else:
                dic[right_value]=right
                right += 1
                sub_len = right - left
                max_len = max(max_len, sub_len)

        return max(max_len, sub_len)


if __name__ == '__main__':

    solution = Solution()
    print(solution.lengthOfLongestSubstring('abcabcbb'))

源代码已上传至 Github,持续更新中。

相关文章

网友评论

    本文标题:Leetcode 3: Longest Substring Wi

    本文链接:https://www.haomeiwen.com/subject/hujnpxtx.html