Leetcode: Word Break II

本文探讨了如何利用递归和动态规划解决字符串拆分问题,即给定一个字符串和一个字典,如何将字符串拆分成字典中存在的有效单词。通过两种方法实现:递归方法和动态规划方法,并对比了它们的时间和空间效率。

摘要生成于 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.

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

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

Use recursion. Note the following code won't be passed in Leetcode due to time limit exceed. Need to see whether the string is breakable or not before calling helper function, which is Word Break.

public class Solution {
    public ArrayList<String> wordBreak(String s, Set<String> dict) {
        ArrayList<String> res = new ArrayList<String>();
        if (s == null || s.length() == 0 || dict.isEmpty() || dict.size() == 0) {
            return res;
        }
        
        int maxLength = 0;
        for (String word : dict) {
            maxLength = Math.max(maxLength, word.length());
        }
        
        helperBreak(s, dict, res, "", maxLength, 0);
        return res;
    }
    
    private void helperBreak(String s, Set<String> dict, ArrayList<String> res, String item, int maxLength, int pos) {
        if (pos == s.length()) {
            res.add(item);
            return;
        }
        
        for (int i = 1; i <= maxLength && i + pos <= s.length(); i++) {
            String word = s.substring(pos, pos + i);
            if (dict.contains(word)) {
                helperBreak(s, dict, res, item.length() >= 1 ? item + " " + word : word, maxLength, pos + i);
            }
        }
    }
 }


Or use dynamic programming. Store the possible sentences ending at each position in an array list, after iteration, return the last element in that array list. This way can save time, but requires much more space.

public ArrayList<String> wordBreak(String s, Set<String> dict) {
        if (s == null || s.length() == 0 || dict.isEmpty() || dict.size() == 0 || !canWordBreak(s, dict)) {
            return new ArrayList<String>();
        }
        
        boolean[] canBreak = new boolean[s.length() + 1];
        canBreak[0] = true;
        ArrayList<ArrayList<String>> sentence = new ArrayList<ArrayList<String>>();
        for (int i = 0; i <= s.length(); i++) {
            sentence.add(new ArrayList<String>());
        }
        sentence.get(0).add("");
        
        int maxLength = 0;
        for (String word : dict) {
            maxLength = Math.max(maxLength, word.length());
        }
        
        for (int i = 1; i <= s.length(); i++) {
            for (int j = 1; j <= maxLength && j <= i; j++) {
                String word = s.substring(i - j, i);
                if (canBreak[i - j] && dict.contains(word)) {
                    canBreak[i] = true;
                    for (String ss : sentence.get(i - j)) {
                    	sentence.get(i).add(ss + (ss == "" ? "" : " ") + word);
                    }
                }
            }
        }
        
        return sentence.get(s.length());
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值