知识点

动态规划

解题思路

使用动态规划,定义dp数组,dp[i]表示位置i之前是否有单词能到达。

将单词数组放到set中,遍历s字符串,再进行i-j的双重循环,截取字符串j到i,如果之前有字符串能到j也就是dp[j]为true,并且set中也包含j到i的字符串,说明能够到达i,即dp[i]为true。最终看dp[n]就是最终答案。

Java题解

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     *
     * @param s string字符串
     * @param wordDict string字符串一维数组
     * @return bool布尔型
     */
    public boolean wordBreak (String s, String[] wordDict) {
        // write code here
        Set<String> wordDictSet = new HashSet<>(Arrays.asList(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; j++) {
                if (dp[j] && wordDictSet.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[s.length()];
    }
}