您的位置:首页 > 编程语言 > Python开发

[LintCode 107] 单词切分(Python)

2017-09-20 14:23 369 查看

题目描述

给出一个字符串s和一个词典,判断字符串s是否可以被空格切分成一个或多个出现在字典中的单词。

样例

给出

s = “lintcode”

dict = [“lint”,”code”]

返回 true 因为”lintcode”可以被空格切分成”lint code”

思路

动规思想。

代码

class Solution:
"""
@param: s: A string
@param: dict: A dictionary of words dict
@return: A boolean
"""
def wordBreak(self, s, dict):
# write your code here
if s is None and dict is None:
return True
if s is None or dict is None:
return False
dp = [False] * (len(s) + 1)
dp[0] = True
for i in range(0, len(s)):
for w in dict:
if dp[i] and (i + len(w) <= len(s)) and s[i:i + len(w)] == w:
dp[i + len(w)] = True
return dp[len(s)]


复杂度分析

时间复杂度O(kn)
9e90
,n为字符串长度,k为字典长度。空间复杂度O(n)。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: