Word Break II

本文介绍了一种使用深度优先搜索(DFS)算法解决字符串构造句子问题的方法,通过哈希集合加速计算并去重,确保了算法效率。具体实现包括定义辅助函数进行递归搜索,并利用缓存技术优化性能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.

Return all such possible sentences.

Example

Example 1:

Input:"lintcode",["de","ding","co","code","lint"]
Output:["lint code", "lint co de"]
Explanation:
insert a space is "lint code",insert two spaces is "lint co de".

Example 2:

Input:"a",[]
Output:[]
Explanation:dict is null.

思路:用dfs 搜索所有的解空间,用memory cache加速;用hashmap去记录一下中间计算的结果,去掉重复计算;

class Solution {
    public List<String> wordBreak(String s, List<String> wordDict) {
        HashSet<String> set = new HashSet<String>(wordDict);
        HashMap<String, List<String>> hashmap = new HashMap<>();
        return dfs(s, set, hashmap);
    }
    
    // s 分成两半
    // prefix + 子问题 -> list of string;
    // prefix + " " + suffix;
    public List<String> dfs(String s, HashSet<String> set, HashMap<String, List<String>> hashmap) {
        if(hashmap.containsKey(s)) {
            return hashmap.get(s);
        }
        List<String> list = new ArrayList<>();
        if(set.contains(s)) {
            list.add(s);
        }
        for(int i = 1; i < s.length(); i++) {
            String prefix = s.substring(0, i);
            if(set.contains(prefix)) {
                for(String suffix: dfs(s.substring(i), set, hashmap)) {
                    list.add(prefix + " " + suffix);
                }
            }
        }
        hashmap.put(s, list);
        return list;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值