代码随想录算法训练营天 第九章 四十六天| 139.单词拆分

代码随想录算法训练营天 第九章 四十六天| 139.单词拆分

139.单词拆分

class Solution {
    public boolean wordBreak(String s, List<String> wordDict) {
        // 这个题感觉很难
        HashSet<String> set = new HashSet<>(wordDict);
        boolean[] dp = new boolean[s.length() + 1];
        dp[0] = true;

        for (int i = 1; i <= s.length(); i++) {
            for (int j = 0; j < i && !dp[i]; j++) {
                if (set.contains(s.substring(j,i)) && dp[j]) {
                    dp[i] = true;
                }
            }
        }
        return dp[s.length()];
    }
}

你可能感兴趣的:(算法,动态规划,leetcode)