[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)。
相关文章推荐
- lintcode(107)单词切分
- lintcode-107-单词切分
- lintcode python 代码 133 最长单词
- LintCode 单词切分
- **[Lintcode]Word Break单词切分
- lintcode,单词切分
- lintcode:单词切分
- LintCode- 单词切分
- LintCode:单词切分
- 单词切分-LintCode
- LintCode:M-单词切分
- lintcode_单词切分
- lintcode 刷题-两数组的交 II Python
- python将每个单词按空格分开
- 最后一个单词的长度---LintCode
- Python(2.7.x)实现简单的单词频数统计
- python将每个单词按空格分开并保存到文件中
- [Python]任一个英文的纯文本文件,统计其中的单词出现的个数。(考虑单词-分行)
- 一个简单的程序,统计文本文档中的单词和汉字数,逆序排列(出现频率高的排在最前面)。python实现。
- 用python从一个单词列表中快速生成word_to_ix字典