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. You may assume the dictionary does not contain duplicate words.
For example, given
Return true because “leetcode” can be segmented as “leet code”.
解法1:DP O(N^2)
经典的用DP的问题,用一个dp数组来记录。dp[i]表示前i个字符是否可能分词。
所以对于每一个dp[i], dp[i] = true if word(0,i) in dict, or dp[k] = true && word(k, i) in dict
这题的坑在于java的substring比较坑,string.substring(j,k)表示从第j个字符到第k-1个字符所组成的substring。
我们这里需要用word(k,i)表示的是第k+1个字符到第i-1个字符。这里容易出错需要注意一下。
Java