二刷139. Word Break

Medium
这道题之前一刷用的dfs做,现在又不会那个方法了,说明我dfs真的弱,现在用dp做一下. 这里dp[i]表示s.substring(0, i)是否满足要求.

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        if (s == null || s.length() == 0){
            return true;
        }
        //dp[i] stands for whether s.substring(0, i) could be segmented into a one or more dictionary words.
        boolean[] dp = new boolean[s.length() + 1];    
        dp[0] = true;
      
        for (int i = 1; i <= s.length(); i++){
            for (int j = 0; j < i; j++){
                if (dp[j] && wordDict.contains(s.substring(j, i))){
                    dp[i] = true;
                    break; 
                }    
            }
        }
        return dp[s.length()];
    }
}
    原文作者:greatfulltime
    原文地址: https://www.jianshu.com/p/f767d4bc32a5
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞