leetcode 140. Word Break II (分割单词II)

本文介绍了一种使用递归和记忆化的算法来解决字符串分割问题的方法。给定一个非空字符串和一个字典,算法将字符串分割成字典中的有效单词,并返回所有可能的分割结果。通过避免重复计算相同子字符串的可能性,提高了算法效率。

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

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, add spaces in s to construct a sentence where each word is a valid dictionary word. Return all such possible sentences.

Note:

The same word in the dictionary may be reused multiple times in the segmentation.
You may assume the dictionary does not contain duplicate words.
Example 1:

Input:
s = “catsanddog”
wordDict = [“cat”, “cats”, “and”, “sand”, “dog”]
Output:
[
“cats and dog”,
“cat sand dog”
]

给出一个字典,一个字符串s,要求用空格把s分割成字典里的单词,要列出所有可能性

思路:
如果单纯用眼睛看来分割,应该是找到以字典单词开头的单词,去掉该单词后继续找下一个字典单词,一个一个去掉再看剩下的,也就是递归。
如果遇到了相同的后面又重复的子字符串,这时候就不需要重复递归,需要一个记忆功能,key是子字符串,value是所有可能性的list,如果要查找的字符串在key里,返回对应value的list即可

class Solution {
    HashMap<String, List<String>> hash = new HashMap<>();
    
    public List<String> wordBreak(String s, List<String> wordDict) {
        if(hash.containsKey(s)) {
            return hash.get(s);
        }
        
        List<String> result = new ArrayList<>();
        
        
        for(String word : wordDict) {
            if(!s.startsWith(word)) {
                continue;
            }
            
            if(s.length() == word.length()) {
                result.add(word);
                continue;
            }
            
            List<String> tmp = wordBreak(s.substring(word.length()), wordDict);
           
            //开头的单词word要和list中每种可能的字符串结合
            for(String str : tmp) {
                String solution = "";
                solution += word;
                solution += " ";
                solution += str;
                result.add(solution);
            }
            
            
        }
            hash.put(s, result);
            
            return result;
        }
        
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

蓝羽飞鸟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值