Skip to content

Instantly share code, notes, and snippets.

@juque
Created December 5, 2023 06:44
Show Gist options
  • Save juque/856efd2df36d7344c1f42ce0940ad967 to your computer and use it in GitHub Desktop.
Save juque/856efd2df36d7344c1f42ce0940ad967 to your computer and use it in GitHub Desktop.
ruby version: Leetcode Longest Substring Without Repeating Characters
# Leetcode: Longest Substring Without Repeating Characters
# ---------------------------------------------------------
#
# script is an implementation of the sliding window technique to find the
# length of the longest substring without repeating characters in a given
# string.
def length_of_longest_substring(s)
# Empty hash to store the last index of each character in the string.
char_index = {}
# This variable represents the starting index of the current window
start_index = 0
# This variable will store the length of the longest substring without repeating characters.
max_length = 0
# it will iterate over each character char in the string s along with its index index.
s.chars.each_with_index do |char, index|
# This line checks if the current character char is already
# in the hash char_index and if its last index is greater
# than or equal to the start_index.
if char_index.key?(char) && char_index[char] >= start_index
# If the condition in the previous line is true, this line updates the
# start_index to be one more than the last index of the current character.
# This ensures that the start_index is moved to the appropriate position
# to exclude any repeating characters within the new window.
start_index = char_index[char] + 1
end
# This line updates the hash char_index to store the current index of the character char.
char_index[char] = index
# This line updates the max_length to be the maximum of the current max_length and
# the length of the current window (which is index - start_index + 1).
max_length = [max_length, index - start_index + 1].max
end
max_length
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment