Skip to content

Instantly share code, notes, and snippets.

@bparanj
Created April 7, 2018 22:15
Show Gist options
  • Save bparanj/2114a79ab1424c6061354690f4381a2c to your computer and use it in GitHub Desktop.
Save bparanj/2114a79ab1424c6061354690f4381a2c to your computer and use it in GitHub Desktop.
require 'set'
def segment_string(s, dictionary, solved)
for i in 1..s.length
first = s[0, i]
if dictionary.include?(first)
second = s[i .. -1]
if (second.length == 0)
return true
end
if dictionary.include?(second)
return true
end
unless solved.include?(second)
if segment_string(second, dictionary, solved)
return true
end
solved.add(second)
end
end
end
false
end
def can_segment_string?(s, dictionary)
solved = Set.new
segment_string(s, dictionary, solved)
end
dictionary = Set['hello', 'hell', 'on', 'now']
p can_segment_string?('wellonow', dictionary)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment