139. 单词拆分

119 阅读1分钟

题目

image.png

方法 dp

image.png

  • 注意边界条件

IMG_152F908BA1F2-1.jpeg

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        Set<String> set = new HashSet<>(wordDict);// 
        boolean[] dp = new boolean[s.length() + 1]; // 前面留个空位
        dp[0] = true; //当0-i的字符串能凑成,就需要空串为true
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i; j++) {
                dp[i] = dp[j] && (set.contains(s.substring(j, i)));
                if (dp[i]) {
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}