Leetcode 140 Word Break 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. You may assume the dictionary does not contain duplicate words.

Return all such possible sentences.

For example, given
s = "catsanddog",
dict = ["cat", "cats", "and", "sand", "dog"].

A solution is ["cats and dog", "cat sand dog"].

这个问题可能由很多不同的组合结果,那么从第index个字母开始,一直到s的末尾,所有可能出现的单词组合用一个list存起来

那么每一个index都对应一个list 所以很自然想到用map



public class Solution {
    private Map<Integer, List<String>> map = new HashMap<>();
    
    public List<String> wordBreak(String s, List<String> wordDict) {
        return helper(s, 0, wordDict);
    }
    
    
    private List<String> helper(String s, int index, List<String> wordDict){
        if(map.containsKey(index)){
            return map.get(index);
        }
        List<String> list = new LinkedList<>();
        if(index == s.length()){//如果当前的index超出s长度 
            list.add("");
        }
        for(int i = index + 1; i <= s.length(); i++){
            String tmp = s.substring(index, i);
            if(wordDict.contains(tmp)){//如果当前substring 是valid的 
               
                List<String> t = helper(s, i, wordDict);//寻找后半部分的list
                for(String str : t){
                    list.add(tmp + (str.equals("") ? "" : " " + str));组合成当前index的一个list
                }
            }
        }
        map.put(index, list);
        return list;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值