[LeetCode][python3]0003. Longest Substring Without Repeating Characters
Start the Journey
N2I -2020.03.15
- 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
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
Explanation:
Most of them are the same with my answer. Which start
replaced 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.