原題地址:https://oj.leetcode.com/problems/word-break/
題意:
Given a string s and a dictionary of words dict, determine if s can be segmented into a space-separated sequence of one or more dictionary words.
For example, given
s = "leetcode",
dict = ["leet", "code"].
Return true because "leetcode" can be segmented as "leet code".
解題思路:這道題考察的顯然不是dfs,為什么?因為這道題不需要給出如何分割的答案,只需要判斷是否可以分割為字典中的單詞即可。我們考慮使用動態規划,這個思路看代碼的話不難,用python寫起來也比較清晰。
代碼:
class Solution: # @param s, a string # @param dict, a set of string # @return a boolean # @good coding! def wordBreak(self, s, dict): dp = [False for i in range(len(s)+1)] dp[0] = True for i in range(1, len(s)+1): for k in range(i): if dp[k] and s[k:i] in dict: dp[i] = True return dp[len(s)]
