2020-01-29 之 139. 单词拆分

2021-01-30  本文已影响0人  止戈学习笔记

题目地址(139. 单词拆分)

https://leetcode-cn.com/problems/word-break/

题目描述

给定一个非空字符串 s 和一个包含非空单词的列表 wordDict,判定 s 是否可以被空格拆分为一个或多个在字典中出现的单词。

说明:

拆分时可以重复使用字典中的单词。
你可以假设字典中没有重复的单词。
示例 1:

输入: s = "leetcode", wordDict = ["leet", "code"]
输出: true
解释: 返回 true 因为 "leetcode" 可以被拆分成 "leet code"。
示例 2:

输入: s = "applepenapple", wordDict = ["apple", "pen"]
输出: true
解释: 返回 true 因为 "applepenapple" 可以被拆分成 "apple pen apple"。
     注意你可以重复使用字典中的单词。
示例 3:

输入: s = "catsandog", wordDict = ["cats", "dog", "sand", "and", "cat"]
输出: false

因为是拆分, 所以S中的字母是不能重复使用的.

/**
 * Created by zcdeng on 2021/1/28.
 */
public class WorkBreak {
    public static void main(String[] args) {
        String s = "catsandog";
        String[] dict = { "o", "cats", "dog", "sand", "and"};
        boolean result = containsInDict(dict, s);
        System.out.println(result);

    }
    private static boolean containsInDict(String[] dict, String s) {
        Map<Integer, Boolean> dp = new HashMap<Integer, Boolean>();
        dp.put(0, true); // 初始状态为true, s长度为零不用单词就能组成

        for (int i = 0; i < s.length() + 1; i++) {
            for (String word : dict) {
                // 从s第零个字母开始扫描字典
                if (word.length() <= i && dp.get(i - word.length()) != null) {
                    // 从字典最短单词开始看, 
                    // 从i - word.length()往前一定要有单词可以拼成, 如果没有根本不用看, 肯定不满足, 当前单词长了或短了
                    if (word.equals(s.substring(i - word.length(), i))) {
                        // 如果i - word.length(), i, 可以在字典找到, 那从i往前都是可以由单词拼成
                        // 标记0-i 可以由单词拼成
                        dp.put(i, true);
                    }
                }
            }
        }

        // 本题的问题即0-s.length是否可以由字典单词构成
        return dp.get(s.length()) != null;
    }
}
上一篇下一篇

猜你喜欢

热点阅读