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

Start the Journey
N2I -2020.03.15

1. My first solution


  1. class Solution:
  2. def lengthOfLongestSubstring(self, s: str) -> int:
  3. if not s:
  4. return 0
  5. dic={}
  6. stuck=0
  7. output=1
  8. for index,item in enumerate(s):
  9. if item not in dic:
  10. dic[item]=index
  11. else:
  12. output=max(output,index-stuck)
  13. stuck=max(dic[item]+1,stuck)
  14. dic[item]=index
  15. output=max(output,len(s)-stuck)
  16. return output
  17.  

2. A better solution


  1. class Solution:
  2. def lengthOfLongestSubstring(self, s: str) -> int:
  3. dicts = {}
  4. maxlength = start = 0
  5. for i,value in enumerate(s):
  6. if value in dicts:
  7. sums = dicts[value] + 1
  8. if sums > start:
  9. start = sums
  10. num = i - start + 1
  11. if num > maxlength:
  12. maxlength = num
  13. dicts[value] = i
  14. return maxlength
  15.  

Explanation:
Most of them are the same with my answer. Which start replaced by stuck (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.