Skip to content

Instantly share code, notes, and snippets.

@JackyChiu
Created September 6, 2019 02:26
Show Gist options
  • Save JackyChiu/89c9a33db0d0ff542694ddbe94751503 to your computer and use it in GitHub Desktop.
Save JackyChiu/89c9a33db0d0ff542694ddbe94751503 to your computer and use it in GitHub Desktop.
# @param {String} s
# @return {Integer}
def length_of_longest_substring(s)
chars = s.split('')
longest = 0
base = 0
char_set = Set.new
(base...chars.length).each do |iter|
while char_set.include?(chars[iter])
# move base up and until the dup char is found
# this acts as a sliding window
char_set.delete(chars[base])
base += 1
end
# increment longest only when no dup
len = iter - base + 1
longest = len if len > longest
char_set.add(chars[iter])
end
longest
end
# expected 3
puts length_of_longest_substring('abcabcbb').inspect
# expected 3
puts length_of_longest_substring('pwwkew').inspect
# same chars, epxected 1
puts length_of_longest_substring('bbb').inspect
# longest in the end, expected 9
puts length_of_longest_substring('pdxdsprlong').inspect
# longest in the front, expected 9
puts length_of_longest_substring('sprlongdxd').inspect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment