139. Word Break(edit)

2018-03-26  本文已影响0人  lqsss

题目

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
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

思路

动态规划的题目,发现自己对最优重复子结构还是模糊。
dp[i]表示长度为i的字符串是否能被完美分割,整个字符串划分:
判断dp[j]&&j之后的字符串是否也能被完美分割

代码

public class wordBreak {
    public boolean wordBreak(String s, Set<String> dict) {
        if (s.length() == 0 || s == null || dict.size() == 0 || dict == null) {
            return false;
        }
        boolean[] dp = new boolean[s.length() + 1]; //dp[i]表示长度为i的字符串是否能被完美分割
        dp[0] = true; //初始值
        for (int i = 1; i <= s.length(); i++) { // 遍历得到所有长度的布尔值
            for (int j = 0; j < i; j++) { //判断是否存在一点可以完美切割当前 长度为i的字符串
                if (dp[j] && dict.contains(s.substring(j, i))) { // s的[0...j)true 且[j,i)在dict可以找到
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}

bfs(//TODO)

上一篇下一篇

猜你喜欢

热点阅读