leetcode: Longest Substring Without Repeating Characters

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode: Longest Substring Without Repeating Characters相关的知识,希望对你有一定的参考价值。

Longest Substring Without Repeating Characters

Given a string, find the length of the longest substring without repeating characters. For example, the longest substring without repeating letters for "abcabcbb" is "abc", which the length is 3. For "bbbbb" the longest substring is "b", with the length of 1.

Analysis

If a repeat char is found, there is no need to search chars before the previous repeat char, so start to search from char after the previous repeat char.

Codes

#!/usr/bin/python

class Solution(object):
    def lengthOfLongestSubstring(self, s):
        """
        :type s: str
        :rtype: int
        """
        d = dict()
        maxLength = 0
        index = 0
        
        while index < len(s):
            if s[index] in d:
                if maxLength < len(d):
                    maxLength = len(d)
                index = d[s[index]] + 1
                d.clear()
            else:
                d[s[index]] = index
                index += 1
                
        if maxLength < len(d):
            maxLength = len(d)
            
        return maxLength

以上是关于leetcode: Longest Substring Without Repeating Characters的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode409. Longest Palindrome

leetcode:longest-increasing

[Leetcode]Longest Palindromic Substring

leetcode longest consecutive sequence

LeetCode Longest Increasing Subsequence

#Leetcode# 14. Longest Common Prefix