[LintCode 107] 单词切分(Python)

题目描述

给出一个字符串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) n 为字符串长度, k 为字典长度。空间复杂度 O(n)

点赞