139. Word Break
problem 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.
Note:
The same word in the dictionary may be reused multiple times in the segmentation. You may assume the dictionary does not contain duplicate words.
Example 1:
Example 2:
Example 3:
algorithm thought
这题可以很快相出回溯解法,匹配到一个进入下一个函数即可,但是这样会有很多重复的计算。
可以用动态规划解决,用一个数组保存结果,每一位表示0-i长度的s能匹配。遍历s,如果当前i开始的substring中,能和wordDict匹配,并且当前dp[i]=true的话,那么substirng的index的是true,最后返回数组最后一位即可
code
algorithm analysis
设s长度为m,wordDict长度为n,每个word平均长度是k,最后时间复杂度是O(mnk)
Last updated