Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How does python find the longest substring without repeating characters

Shulou Source: shulou.com Published: 2022-05-31 14:07:57 10月02日 Update

This article mainly introduces the relevant knowledge of "how to find the longest substring of non-repetitive characters in python". The editor shows you the operation process through an actual case. The method of operation is simple and fast, and it is practical. I hope this article "how to find the longest substring of non-repetitive characters in python" can help you solve the problem.

[title]

Given a string, please find out the length of the longest substring that does not contain repeating characters.

Example 1:

Enter: "abcabcbb"

Output: 3

Explanation: because the longest substring of non-repeating characters is "abc", its length is 3.

Example 2:

Enter: "bbbbb"

Output: 1

Explanation: because the longest substring of non-repeating characters is "b", its length is 1.

Example 3:

Enter: "pwwkew"

Output: 3

Explanation: because the longest substring of non-repeating characters is "wke", its length is 3.

Please note that your answer must be the length of the substring. "pwke" is a subsequence, not a substring.

[ideas]

1. Brute force cracking: a two-layer for loop traverses all substrings to determine whether there are repetitive elements and record the longest substring length.

2. Hash table: traverses the array, using hash to store elements and their subscripts. When traversing, when the element nums [I] exists in the hash table, the subscript needs to be updated, as well as the longest substring length.

[code]

Python version

Class Solution:

Def lengthOfLongestSubstring (self, s: str)-> int:

D = {}

Last_index = 0

Res = 0

For I, si in enumerate (s):

# in dict, the substring length may be longer

# last_index updated to d [si] + 1

If si ind and d [si] > = last_index:

Res = max (res, I-last_index)

Last_index = d [si] + 1

# Update the si of dict

D [si] = I

# Note, it has not been compared with the last paragraph

Res = max (res, len (s)-last_index)

This is the end of return res's introduction to "how python finds the longest substring without repeating characters". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Tags: Longest character length update element knowledge example interpretation input output subscript industry different practical size code content at the same time string utility Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi OPPO Reno MariaDB Linux Shulou Information