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)