Skip to content

Instantly share code, notes, and snippets.

@Devligue
Last active July 3, 2018 22:11
Show Gist options
  • Save Devligue/fdf0e171d3d54ce1dbb9da770ffc7a36 to your computer and use it in GitHub Desktop.
Save Devligue/fdf0e171d3d54ce1dbb9da770ffc7a36 to your computer and use it in GitHub Desktop.
INTERVIEW: Determine if string can be splitted into sentence using words in provided list.

Given a non-empty string s and a list word_list containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the word_list does not contain duplicates, but each word can be used more than once.

For example, given:

s = 'whataniceday'
word_list = ['a', 'what', 'an', 'nice', 'day']

Return True, because 'whataniceday' can be segmented as 'what a nice day'.

s = "whataniceday"
word_list = ["h", "a", "what", "an", "nice", "day"]
def can_be_segmented(s, word_list):
tested_str = s
buildup_str = ''
for letter in tested_str:
buildup_str += letter
if buildup_str not in word_list:
continue
tested_str = tested_str[len(buildup_str):]
buildup_str = ''
return bool(tested_str == '' and buildup_str == '')
print(can_be_segmented(s, word_list))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment