Skip to content

Instantly share code, notes, and snippets.

@woodRock
Created August 28, 2018 11:26
Show Gist options
  • Save woodRock/2ad1cad98192df162ce4996401c8a561 to your computer and use it in GitHub Desktop.
Save woodRock/2ad1cad98192df162ce4996401c8a561 to your computer and use it in GitHub Desktop.
Given an integer k and a string s, find the length of the longest substring that contains at most k distinct characters. For example, given s = "abcba" and k = 2, the longest substring with k distinct characters is "bcb".
#!/usr/bin/env ruby
require 'set'
def distinct_char(s,k)
#assert(len(s) >= k)
start_idx, end_idx, max_length = 0, k, k
while end_idx < s.length do
end_idx += 1
while true do
distinct_chars = s[start_idx,end_idx].split(//).to_set().length
if distinct_chars <= k
break
end
start_idx += 1
end
max_length = [max_length, end_idx - start_idx].max
end
return max_length
end
if __FILE__ == $0
s = "aabbcc"
k = 2
puts distinct_char(s,k)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment