牛客网:单词分割
题目描述
Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
输入描述:
s =“catsanddog”
dict =“cat”, “cats”, “and”, “sand”, “dog”
输出描述:
[cats and dog, cat sand dog]
用递归来做:
- 每次在dict中查找s的开头单词,如果找到符合条件的单词,就将其记录在结果中。
- 找到合适的单词后,就从上次找到的单词的下一位开始递归查找。直至s为空字符为止。
import sys
def dfs(s, dic, arr, ans):
if not s:
ans.append(' '.join(arr))
for w in dic:
if s.startswith(w):
dfs(s[len(w):], dic, arr + (w,), ans)
if __name__ == "__main__":
s = raw_input().strip()
s = s[s.index('"') + 1:-1]
dic = raw_input().strip()
dic = eval("{" + dic[dic.index('"'):] + "}")
ans = []
dfs(s, dic, tuple(), ans)
print('[' + ', '.join(ans) + ']')