Ruka
2 min readMar 14, 2020

[LeetCode][python3]0003. Longest Substring Without Repeating Characters

Start the Journey
N2I -2020.03.15

  1. My first solution
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:

if not s:
return 0
dic={}
stuck=0
output=1
for index,item in enumerate(s):
if item not in dic:
dic[item]=index
else:
output=max(output,index-stuck)
stuck=max(dic[item]+1,stuck)
dic[item]=index
output=max(output,len(s)-stuck)
return output
N2I -2020.03.15

2. A better solution

class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
dicts = {}
maxlength = start = 0
for i,value in enumerate(s):
if value in dicts:
sums = dicts[value] + 1
if sums > start:
start = sums
num = i - start + 1
if num > maxlength:
maxlength = num
dicts[value] = i
return maxlength
N2I -2020.03.15

Explanation:

Most of them are the same with my answer. Which startreplaced bystuck(cause the duplicate char stuck the string to be longer in my words). Biggest different in using Max() function, not using it may low down your cost.

Ruka
Ruka

Written by Ruka

HI I’m Ruka. Now a SWE in Taiwan. Contact via email: nayzi9999@gmail.com

No responses yet