单词分割

牛客网:单词分割
题目描述
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]

用递归来做:

  1. 每次在dict中查找s的开头单词,如果找到符合条件的单词,就将其记录在结果中。
  2. 找到合适的单词后,就从上次找到的单词的下一位开始递归查找。直至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) + ']')

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值