1. 程式人生 > >python leetcode 139. Word Break 140. Word Break II

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]