-
BingoPython解法一:
class Solution: # @param s, a string # @param wordDict, a set<string> # @return a boolean def wordBreak(self, s, wordDict): queue = [s] visitSet = set([s]) while queue: front = queue.pop(0) if front in wordDict: return True prefix = '' for c in front: prefix += c suffix = front[len(prefix):] if prefix in wordDict and suffix not in visitSet: queue.append(suffix) visitSet.add(suffix) return False
-
BingoPython解法二:
class Solution: # @param s, a string # @param wordDict, a set<string> # @return a boolean def wordBreak(self, s, words): ok = [True] for i in range(1, len(s)+1): ok += any(ok[j] and s[j:i] in words for j in range(i)), return ok[-1]
-
BingoJava:
public class Solution { public boolean wordBreak(String s, Set<String> wordDict) { boolean[] dp = new boolean[s.length()+1]; Arrays.fill(dp,false); dp[s.length()]=true; // 外层循环递增长度 for(int i = s.length()-1; i >=0 ; i--){ // 内层循环寻找分割点 for(int j = i; j < s.length(); j++){ String sub = s.substring(i,j+1); if(wordDict.contains(sub) && dp[j+1]){ dp[i] = true; break; } } } return dp[0]; } }
-