Word Break II

本文介绍了一种使用深度优先搜索(DFS)算法解决字符串拆分问题的方法,并通过加入备忘录来优化性能。该问题要求将给定字符串通过字典中的词汇进行拆分,并返回所有可能的拆分组合。

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

题目描述:

Given a string s and a dictionary of words dict, add spaces ins 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"].

dfs会超时:

public class Solution {
    public List<String> wordBreak(String s, Set<String> wordDict) {
		List<String> result=new ArrayList<String>();
		StringBuilder sb=new StringBuilder();
		getScentence(s, wordDict, 0, sb, result);
		return result;
    }
	
	public void getScentence(String s, Set<String> wordDict,int start,StringBuilder sb,List<String> result){
		if(start==s.length()){
			int len=sb.length();
			String str=sb.delete(len-1, len).toString();
			result.add(str);return;
		}
		int len=sb.length();
		for(int i=start+1;i<=s.length();i++){
			String substr=s.substring(start, i);
			if(wordDict.contains(substr)){
				sb.append(substr).append(" ");
				getScentence(s, wordDict, i, sb, result);
				sb.delete(len, len+substr.length()+1);//这里要+1,小心细节- -!
			}
		}
	}
} 
带备忘录的dfs算法:
public class Solution {
    Map<String, List<String>> mem = new HashMap<>();
	public List<String> wordBreak(String s, Set<String> wordDict) {
	    if (mem.get(s) != null) return mem.get(s);
	    List<String> result = new ArrayList<>();
	    if (wordDict.contains(s)) result.add(s);
	    for (int i = 1; i < s.length(); i++) {
	        String word = s.substring(0, i);
	        if (wordDict.contains(word)) {
	            List<String> tmp = wordBreak(s.substring(i), wordDict);
	            for (String str : tmp) {
	                result.add(word + " " + str);
	            }
	        }
	    }
	    mem.put(s, result);
	    return result;
	}
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值