zoukankan      html  css  js  c++  java
  • 单词拆分II

    #单词拆分II
    #给一字串s和单词的字典dict,在字串中增加空格来构建一个句子,并且所有单词都来自字典。
    #返回所有有可能的句子。
    #EXAMPLE:
    #给一字串lintcode,字典为["de", "ding", "co", "code", "lint"]
    #结果为["lint code", "lint co de"]。

    class Solution:
        """
        @param: s: A string
        @param: wordDict: A set of words.
        @return: All possible sentences.
        """
        def wordBreak(self, s, wordDict):
            # write your code here
            return self.helper(s, wordDict, {})

        def helper(self, s, wordDict, memory):
            if s in memory: #string如果有记录,直接调用返回以节省时间
                return memory[s]
            res = []
            for i in range(len(s)-1):
                cut = s[:i+1]
                if cut in wordDict:
                    sub = self.helper(s[i+1:], wordDict, memory)
                    for j in sub:
                        res.append(cut + ' ' + j)
            if s in wordDict:
                res.append(s)
            memory[s] = res #记住这个string有多少种拆分方法
            return res

  • 相关阅读:
    Session共享的解决方案
    用IIS配置反向代理
    authorization配置
    git之https或http方式设置记住用户名和密码的方法
    微信分享接口
    为你的Visual Studio单独设置代理服务器
    HTTP错误404.13
    MVC5的AuthorizeAttribute详解
    【MVC5】画面多按钮提交
    PetaPoco dynamic
  • 原文地址:https://www.cnblogs.com/phinza/p/10313643.html
Copyright © 2011-2022 走看看