Longest Substring Without Repeating Characters, longestrepeating
Today, I started to record leetcode and write it in a simple way. Sorry.
Longest Substring Without Repeating Characters
Question:
Given a string, find the length of the longest substring without repeating characters.
Given a string, find its longest non-repeated substring
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"
IsSubsequenceAnd not a substring.
I read a method on the Internet, which is very interesting. The time complexity is o (n). First, the parameter m is a list with a size of 256. You can store the corresponding location of each character in the string based on ascii.
Example: 'aab'-> m [97] = 0, m [65] = 1, m [98] = 2
Max res record length
Start is used to record the starting position of substring
When s [I] appears for the first time, m [ord (s [I])] = 0
Or s [I] appears multiple times, but when the starting position is greater than the previous location where the same character appears, res is updated.
Res = max (res, I-start + 1)
Otherwise, update the start position to the location where the same characters appear.
1 class Solution(object): 2 def lengthOfLongestSubstring(self, s): 3 """ 4 :type s: str 5 :rtype: int 6 """ 7 m = [0]*256 8 res = 0 9 start = 010 for i in range(len(s)):11 c = ord(s[i])12 if (m[c] == 0 or m[c]<start):13 res = max(res,i+1-start)14 else:15 start = m[c]16 m[c] = i+117 return res
References:
[LeetCode] Longest Substring Without Repeating Characters