python leetcode 139. Word Break 140. Word Break II

139. Word Break

class Solution:
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: bool
        """
        if not s: return True
        if not wordDict: return False
        wmin=1000
        wmax=-1
        wdict={}
        for w in wordDict:
            wdict[w]=True 
            wmin=min(len(w),wmin)
            wmax=max(len(w),wmax)
        dp=[False]*(len(s)+1)
        dp[0]=True
        for i in range(1,len(s)+1):
            for l in range(wmin,wmax+1):
                j=i+l-1
                if j<=len(s) and s[i-1:j] in wdict and dp[i-1]:
                    dp[j]=True 
                    
        return dp[-1]

140. Word Break II 方法类似于回文划分

注意先要判断能否划分,不然会超时

class Solution:
    def wordBreak(self, s, wordDict):
        """
        :type s: str
        :type wordDict: List[str]
        :rtype: List[str]
        """
        wmin=1000
        wmax=-1
        wdict={}
        for w in wordDict:
            wdict[w]=True 
            wmin=min(len(w),wmin)
            wmax=max(len(w),wmax)
        if not self.can(s,wdict,wmin,wmax): return []
        dp=[[] for _ in range((len(s)+1))]
        dp[0]+=['']
        for i in range(1,len(s)+1):
            for l in range(wmin,wmax+1):
                j=i+l-1
                if j<=len(s) and s[i-1:j] in wdict and len(dp[i-1])>0:
                    for tmp in dp[i-1]:
                        if tmp=='': tmp+=s[i-1:j]
                        else: tmp=tmp+' '+s[i-1:j]
                        dp[j].append(tmp)
        return dp[-1]
    def can(self,s,wdict,wmin,wmax):
        dp=[False]*(len(s)+1)
        dp[0]=True
        for i in range(1,len(s)+1):
            for l in range(wmin,wmax+1):
                j=i+l-1
                if j<=len(s) and s[i-1:j] in wdict and dp[i-1]:
                    dp[j]=True 
        return dp[-1]

你可能感兴趣的:(leetcode,python)