Commit 68a2dcc
Changed files (1)
2022
04
11
2022/04/11/main.rb
@@ -0,0 +1,39 @@
+#!/usr/bin/env ruby
+
+=begin
+Given a string, find the length of the longest substring without repeating characters.
+
+class Solution:
+ def lengthOfLongestSubstring(self, s):
+ # Fill this in.
+
+print Solution().lengthOfLongestSubstring('abrkaabcdefghijjxxx')
+# 10
+
+Can you find a solution in linear time?
+=end
+
+def assert_equal(x, y)
+ raise [x, y].inspect unless x == y
+end
+
+class Solution
+ def self.length_of_longest_substring(value)
+ last = nil
+ count = 0
+ max = 0
+ value.chars.each_with_index do |char, i|
+ if char == last
+ count = 1
+ else
+ count += 1
+ end
+ max = count if count > max
+ last = char
+ end
+ max
+ end
+end
+
+assert_equal 10, Solution.length_of_longest_substring('abrkaabcdefghijjxxx')
+puts "Yay!"