Leetcode_3 Longest Substring Without Repeating Characters

Description

Given a string, find the length of the longest substring without repeating characters.
Example 1:
Input: “abcabcbb”
Output: 3
Explanation: The answer is “abc”, with the length of 3.

Example 2:

Input: “bbbbb”
Output: 1
Explanation: The answer is “b”, with the length of 1.

Example 3:

Input: “pwwkew”
Output: 3
Explanation: 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.

Solution1

1
2
3
4
5
6
7
8
9
10
11
12
class Solution:
def lengthOfLongestSubstring(self, s):
seen = {}
max_len = 0
start = 0
for i, c in enumerate(s):
if c in seen and seen[c] >= start:
if i-start > max_len:
max_len = i-start
start = seen[c]+1
seen[c] = i
return max(max_len, len(s)-start)

Solution2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution():
def lengthOfLongestSubstring(self, s):
"""
:type s: str
:rtype: int
"""
maxnum,num,ss =0,0,''
for each in s:
if each in ss:
ss = ss.split(each)[-1]+each
num =len(ss)
else:
num += 1
ss += each
if num>=maxnum:
maxnum = num

return maxnum
-------------End of the articleThank you for reading-------------
  • Author of this article:zfish
  • Link to this article: archives/a43781b9.html
  • Copyright Notice: All articles in this blog, except for special statements, please indicate the source!
0%