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".

开始想用递归来解决,时间复杂度太高,于是想到用动态规划,创建一个boolean数组dp[], dp[i]代表字符串前i个字符在dict中,但不一定是包含s.substring(0, i + 1), 只是包含了一种或几种可能的解,然后我们检查i后面的元素,如果后面的字符串不能被dict包含,这是我们从前面找另一个可能的起始点,然后继续查找。代码如下:
public class Solution {
    public boolean wordBreak(String s, Set<String> wordDict) {
        if(s == null) return false;
        boolean[] dp = new boolean[s.length()];
        for(int i = 0; i < dp.length; i++) {
            if(dp[s.length() - 1]) break;
            if(wordDict.contains(s.substring(0, i + 1))) 
                dp[i] = true;
            if(dp[i]) {
                for(int j = i + 1; j < dp.length; j++) {
                    if(wordDict.contains(s.substring(i + 1, j + 1)))
                        dp[j] = true;
                }
            }
        }
        return dp[s.length() - 1];
    }
}

你可能感兴趣的:(动态规划)