zoukankan      html  css  js  c++  java
  • 139. Word Break

    https://leetcode.com/problems/word-break/#/description

    Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

    For example, given
    s = "leetcode",
    dict = ["leet", "code"].

    Return true because "leetcode" can be segmented as "leet code".

    UPDATE (2017/1/4):
    The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

    Sol:

    DP.

    Straightforward. Split the input string s into all possible two substrings and check if them are in the word dictionary.

    Create a status variable dp to track if string s[:i+1] can be splited into two words of the word dictionary. You see, we track the string bit by bit and the next status is based on the previous status. The last status is our concern, and the last element in dp[-1] will be returned. 

     

    class Solution(object):
        def wordBreak(self, s, wordDict):
            """
            :type s: str
            :type wordDict: List[str]
            :rtype: bool
            """
            
            # dp[i] means s[:i+1] can be segmented into words in the wordDicts
            dp = [False] * (len(s) + 1)
            dp[0] = True
            for spliter1 in range(len(s)):
                for spliter2 in range(spliter1, len(s)):
                    if dp[spliter1] and s[spliter1: spliter2 + 1] in wordDict:
                        dp[spliter2 + 1] = True
                        
            return dp[-1]
  • 相关阅读:
    ICPC-Beijing 2006 狼抓兔子
    【模板】多项式求逆
    AHOI2014/JSOI2014 奇怪的计算器
    Hnoi2013 切糕
    Ahoi2014&Jsoi2014 支线剧情
    bzoj3774 最优选择
    WC2019游记
    HNOI2007 分裂游戏
    bzoj1457 棋盘游戏
    poj2484 A Funny Game
  • 原文地址:https://www.cnblogs.com/prmlab/p/7133049.html
Copyright © 2011-2022 走看看