python:字符串分割word-break

1、给定字符串s,列表t,其中的元素也是字符串,判断s是否可以分割成t中的一个或多个元素。例如:

s='csdncode', t=['csdn','python','code'], output:True

代码如下:

def wordBreak(s, t):
    ok = [True] # ok[j] 表示:s[:j] 是否可以分割成t中的元素。
    # 我们从s[0]开始进行判断一直到s[:]
    for i in range(1, len(s)+1):
        ok += any(ok[j] and s[j:i] in t for j in range(i)),
        # 利用已经判断过的ok[j] 以及s[j:i]是否在t中 来判断s[:i]  
    return ok[-1]

2、同样给定s与t,要求给出所有可能的分割情况,如:

s='csdnandpython', t=['csdn','and','python','cs','dnand']
output:[['csdn', 'and', 'python'], ['cs', 'dnand', 'python']]

代码如下:

def wordBreak2(self, s, wordDict):
    # sentence(i)表示s[i:]可能分割的情况
    memo = {len(s): ['']}
    def sentences(i):
        if i not in memo:
           memo[i] = [s[i:j] + (tail and ' ' + tail)
                       # 判断 tail是否为空
                       for j in range(i+1, len(s)+1)
                       if s[i:j] in wordDict
                       for tail in sentences(j)]
        return memo[i]
    return sentences(0)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值