【算法训练】LeetCode#139 单词拆分

一、描述

139. 单词拆分

给你一个字符串 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

二、思路

读完题之后想到的就是暴力递归...不过显然会出现超时问题。

  • v2:不断尝试wordDict并且没做剪枝操作,所以超时,因此v2尝试拿s不断尝试,并通过动态规划记录历史匹配数据,减少比较次数。

三、解题

public class LeetCode139 {

    public static boolean wordBreakV1(String s, List<String> wordDict) {
        return processV1(s,wordDict);
    }

    // 递归尝试能否拆分
    public static boolean processV1(String s,List<String> wordDict){
        if ("".equals(s)){
            return true;
        }

        for (int i = 0 ; i < wordDict.size() ; i++){
            int index = s.indexOf(wordDict.get(i));
            if (index == 0){
                // 从头往后匹配
                if (processV1(s.substring(wordDict.get(i).length()),wordDict)){
                    // 截断单词继续匹配
                    return true;
                }
            }
        }
        return false;
    }
    public static boolean wordBreakV2(String s, List<String> wordDict) {
        HashSet<String> map = new HashSet<>(wordDict);
        int n = s.length(); // 字符串长度
        boolean[] dp = new boolean[n+1]; // 动态规划数组,dp[i]表示字符串在0..i上(不包括i)能够被表示
        dp[0] = true;
        for (int i = 1 ; i < n+1 ; i++){
            for (int j = 0 ; j < i ; j++){
                if (dp[j] && map.contains(s.substring(j,i))){
                    // 只要在0..i上满足0..j、j..i能够被表达,那0..i一定能被表达
                    dp[i] = true;
                    break;
                }
            }
        }
        return dp[n];
    }

}
posted @ 2023-02-09 13:05  小拳头呀  阅读(24)  评论(0编辑  收藏  举报