leetcode-面试题-17.13-恢复空格

题目描述:

 

 

 

 方法一:动态规划 O(n2) ->O(mn) m为字典中单词最大长度

class Solution:
    def respace(self, dictionary: List[str], sentence: str) -> int:
        d = {}.fromkeys(dictionary)
        n = len(sentence)
        mxl = max([len(i) for i in dictionary])
        #print(mxl)
        f = [0] * (n + 1)
        for i in range(1, n + 1):
            f[i] = f[i - 1] + 1
            for j in range(max(0,i-mxl),i):
                if sentence[j:i] in d:
                    f[i] = min(f[i], f[j])
        return f[-1]

 

posted @ 2020-07-10 08:51  oldby  阅读(121)  评论(0编辑  收藏  举报