Leetcode 3. Longest Substring without repeating characters (Python version)

Source: Internet
Author: User

Topic:

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

The main idea is to find the longest non-repeating substring


Algorithm ideas:

This problem should be able to use dynamic programming, I use a double point method

One pointer start pointing to the substring header, the other pointer end pointing to the tail of the substring

Increments end each time to determine whether the character in the end is present in the current substring.

      • If it appears, move the start pointer backward one

      • Otherwise, move the end pointer backwards and update the oldest string length

Finally, the maximum length of the substring is returned.


The algorithm can be optimized when the start pointer is moved, but I find that the result is not changed after optimization, just stick to the original code.


Code:

Class solution (object):     def lengthoflongestsubstring (self, s):          "" "        :type s:  str        :rtype: int          "" "        slen = len (s)          if sLen == 0 or sLen == 1:             return sLen         letters = list (s)         hashSet = {}         hashSet[letters[0]] = 1         start = 0        end = 1       &nBsp; maxlen = 1        while end != slen :            letter = letters[end]             if hashset.has_key (letter)  and  hashSet[letter] > 0:                 hashSet[letters[start]] -= 1                 start += 1                 continue             hashSet[letter] = 1             end += 1             if end - start > maxLen:                 maxLen = end - start         return maxlen


This article is from the "Temperature" blog, please be sure to keep this source http://wdswds.blog.51cto.com/11139828/1737802

Leetcode 3. Longest Substring without repeating characters (Python version)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.