Longest Substring Without Repeating Characters, longestrepeating

Source: Internet
Author: User

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

 

Related Article

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.