LeetCode-139. 单词拆分-Java-medium

题目链接

法一(动态规划)
    /**
     * 法一(动态规划)
     * 分析:
     * (1)字符串s相当于背包,wordDict相当于物品,能否利用单词拼接出字符串s就可以转化为能否用物品填满背包
     * (2)由于单词可以重复使用,因此属于完全背包问题
     * 思路:
     * (1)确定dp数组以及下标的含义
     *      dp[i]表示字符串s的前i个字符能否拆分成wordDict
     * (2)确定递推公式
     *     if(dp[j] == true && [j, i]这个区间的子串出现在wordDict中),则dp[i] = true
     * (3)确定dp数组如何初始化
     *     dp[0]初始化为true,其他初始化为false
     * (4)确定遍历顺序
     *     最好先遍历背包,在遍历物品,因为是完全背包所以内循环从前往后遍历
     * 时间复杂度:O(n^3)
     * 空间复杂度:O(n)
     *
     * @param s
     * @param wordDict
     * @return
     */
    public boolean wordBreak(String s, List<String> wordDict) {
        int len = s.length();
        boolean[] dp = new boolean[len + 1];
        dp[0] = true;
        for (int i = 1; i <= len; i++) {   // 遍历背包(s)
            for (int j = 0; j < i; j++) {  // 遍历物品(wordDict)
                if (dp[j] && wordDict.contains(s.substring(j, i))) {
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[len];
    }
本地测试
        /**
         * 139. 单词拆分
         */
        lay.showTitle(139);
        Solution139 sol139 = new Solution139();
        String s139 = "applepenapple";
        String[] wordDictArr139 = {"apple", "pen"};
        List<String> wordDict139 = Arrays.asList(wordDictArr139);
        System.out.println(s139);
        arrayOpt.showStringList(wordDict139);
        System.out.println(sol139.wordBreak(s139, wordDict139));

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