Skip to content

Instantly share code, notes, and snippets.

@rvalenciano
Last active September 11, 2015 06:14
Show Gist options
  • Save rvalenciano/6db3f383168b405bfd03 to your computer and use it in GitHub Desktop.
Save rvalenciano/6db3f383168b405bfd03 to your computer and use it in GitHub Desktop.
Repeated Substring
def f(s)
#your code here
substring = s.scan(/(.+)\1+/)
unless substring.empty? || substring.first.first.size == 1
temp = temp2 = substring
loop do
break if temp2.empty?
temp2 = temp.first.first.scan(/(.+)\1+/)
unless temp2.empty?
temp = temp2
end
end
temp = temp.first.first
number_of_ocurrences = s.scan(temp).size
substring = [temp]
substring << number_of_ocurrences
else
substring = [s]
substring << 1
end
substring
end
@rvalenciano
Copy link
Author

Description

For a given nonempty string s find a minimum substring t and the maximum number k, such that the entire string s is equal to t repeated k times. The input string consists of lowercase latin letters. Your function should return a tuple (in Python) (t, k) or an array (in Ruby and JavaScript) [t, k]

Test Cases

Test.assert_equals(f("ababab"), ["ab", 3])
Test.assert_equals(f("abcde"), ["abcde", 1])

Elegant Solution

def f(s)
  r = s.scan(/(.{2,}?)\1+/)
  (r.empty?)? [s,1] : [r[0][0],s.scan(/#{r[0][0]}/).size]
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment