Created
March 29, 2024 15:07
-
-
Save codertcet111/ac95c4e803f93b2227268109a6160b92 to your computer and use it in GitHub Desktop.
Leetcode 3: Longest substring without repeating character
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Leetcode 3: Longest substring without repeating character | |
# @param {String} s | |
# @return {Integer} | |
def length_of_longest_substring(s) | |
return 0 if s == "" || s == nil | |
arr = s.split("") | |
curr_count = 1 | |
max_len = 1 | |
curr_arr = [arr[0]] | |
(1..(arr.length - 1)).each do |i| | |
if curr_arr.any?(arr[i]) | |
curr_arr = curr_arr[(curr_arr.find_index(arr[i]) + 1)..-1] << arr[i] | |
curr_count = curr_arr.length | |
else | |
curr_arr << arr[i] | |
curr_count += 1 | |
end | |
max_len = [curr_count, max_len].max | |
end | |
max_len | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment