1.Descriptions
Given a string, find the length of the longest substring without repeating characters.
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"
is a subsequence and not a substring.
2.Solution
I am not going to use any complex algorithm to solve this problem so I just utilize some fundamental marks to illustrate the problems. Here are some key steps you would need to focus on:
1. You need to create a container first to contain our desired substring and ultimate length.
2. So next problem we want to solve is that when we should update our container and length. In this step we can easily use our python edge over set manipulation. So we can judge when the length of original list b is equaled to the length of set(b). Then we have to take out the first index of lastly appended element then stored it in a variable named index and index can be used to delete first appearances of aimed element and then store this loop's content into a variable named str_content . If new added element is unique and we can do another judgement to justify whether its length is bigger than the one we stored in the length variable. And if the answers is yes and we can update the length and str_content to ensure that successful running.
3.Code
class Solution:
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
b = []
if s:
length = 1
else:
length = 0
for i in s:
b.append(i)
if len(b) != len(set(b)):
index = b.index(i)
if length < len(b) - 1:
length = len(b) - 1
str_content = ''.join(b[0:-1])
b = b[index + 1:]
# print(set(b))
else:
if len(b) >= length:
length = len(b)
str_content = ''.join(b)
# self.length = length
return length