Содержание
Вопрос
- Дана строка
s
, найдите длину самой длинной подстроки без повторяющихся символов.
Пример
- Пример 1:
Вход: s = «abcabcbb»
Выходные данные: 3
Пояснения: Ответом является «abc», длина которого равна 3.
- Пример 2:
Вход: s = «bbbbbb»
Выход: 1
Пояснения: Ответом является «b», длина которого равна 1.
- Пример 3:
Вход: s = «pwwkew»
Выход: 3
Пояснения: Ответом является «wke», длина которого равна 3.
Обратите внимание, что ответ должен быть подстрокой, «pwke» — это подпоследовательность, а не подстрока.
Ограничения:
-
0 <= s.length <= 5 * 104
-
s
состоит из английских букв, цифр, символов и пробелов.
Моя попытка
Попытка 1 (провал в двух последних случаях, превышен лимит времени)
- алгоритм
>Find the length of the longest substring without repeating characters.
initialise the length_of_s equals to length of s
initialise the length_list_of_sub_string to the empty string
define a find_and_record_substring program:
initialise seen_string as an empty string
initialise seen_dictionary as an empty dictionary
initialise the length equals to 0
for each character in s:
if the charcter do not found in seen_string:
add the character to seen_string
otherwise:
initialise the length equals to length of seen_string
update seen_dictionary with length as key, seen_string as value
set seen_string to empty string
add the character to seen_string
return the maximum of the key of the dictionary
>>find and record each substring without repeating characters in the string s
repeat the find_and_record_substring program for the length of s times:
add the result of find_and_record_substring program to length_list_of_sub_string
set s to a s that remove the first character
>>return the longest substring without repeating characters
return longest length equals to the maximum of length_list_of_sub_string
- код
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length_of_s = len(s)
length_list_of_sub_string = []
# program to find each substring without repeating characters in the string
def find_and_record_substring(str1: str):
seen_string = ""
seen_dict = {}
for char in str1:
if char not in seen_string:
seen_string += char
# if char found in seen_string
else:
# add the current seen_string to dict first
length_of_seen_string = len(seen_string)
seen_dict.update({length_of_seen_string: seen_string})
# clear the seen_string and continue to build seen_string
seen_string = ""
seen_string += char
# should add the current seen_string to dict
length_of_seen_string = len(seen_string)
seen_dict.update({length_of_seen_string: seen_string})
longest_length = max(seen_dict.keys())
return longest_length
if s == "":
return 0
while length_of_s != 0:
length_list_of_sub_string.append(find_and_record_substring(s))
# remove the first charcter of s
s = s[1::]
# update the length of s
length_of_s = len(s)
return max(length_list_of_sub_string)
Попытка 2 (успех)
- в принципе, то же самое, что и выше, но добавьте функцию для нахождения верхней границы подстроки, которая равна количеству уникальных символов в строке s.
- и когда любая подстрока достигнет верхнего предела, функция не будет двигаться дальше и вернет длину подстроки.
- код
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
length_of_s = len(s)
length_list_of_sub_string = []
temp_max = 0
def longest(str1):
set1 = set(str1)
return len(set1)
max_limit = longest(s)
def find_and_record_substring(str1: str):
seen_string = ""
seen_dict = {}
for char in str1:
if char not in seen_string:
seen_string += char
else:
length_of_seen_string = len(seen_string)
seen_dict.update({length_of_seen_string: seen_string})
seen_string = ""
seen_string += char
length_of_seen_string = len(seen_string)
seen_dict.update({length_of_seen_string: seen_string})
longest_length = max(seen_dict.keys())
return longest_length
if s == "":
return 0
while length_of_s != 0 and temp_max < length_of_s and temp_max < max_limit:
length_list_of_sub_string.append(find_and_record_substring(s))
s = s[1::]
length_of_s = len(s)
temp_max = max(length_list_of_sub_string)
return max(length_list_of_sub_string)
Другое решение
- гораздо более быстрое решение на Red Crack
def lengthOfLongestSubstring(s: str) -> int:
# Base condition
if s == "":
return 0
# Starting index of window
start = 0
# Ending index of window
end = 0
# Maximum length of substring without repeating characters
maxLength = 0
# Set to store unique characters
unique_characters = set()
# Loop for each character in the string
while end < len(s):
if s[end] not in unique_characters:
unique_characters.add(s[end])
end += 1
maxLength = max(maxLength, len(unique_characters))
else:
unique_characters.remove(s[start])
start += 1
return maxLength
Мое размышление
- Сегодня я изучаю новый алгоритм под названием Sliding Window Algorithm.
Кредит
- leetcode3