Leetcode - WordBreak III

本文介绍了一种基于回溯算法的字符串分割匹配方法,该方法旨在判断一个字符串是否能被分割成一个或多个字典中出现的单词序列,并且每个字典中的单词只能使用一次。通过递归方式实现,详细展示了如何利用回溯思想解决这一问题。

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

Given a string s and a dictionary of words dict, determine if s can be segmented into a sequence of one or more dictionary words.

   But notice that each word in the dictionary can be used at most once.

For example:

  the dictionary is {"leet", "co" "de" "code"}

  It can match "leetcode", can match “leetcodecode”,but can’t match “leetleetcode”
 [分析] 此题为yb君改编,改编后的题目不能采用动态规划来做,动态规划要求问题的各求解方案是独立平行的,改编后一步决策会影响下一步,因此需要回溯。思维混乱或者貌似空白时把每一点想法尽可能的描述出来,这非常有助于形成完整的思路。

 

boolean IsComposible(Set<String> dict, String s) {
	if (dict == null || s == null || s.length() == 0)
		return false;
	if (dict.contains(s))
		return true;
	int n = s.length();
	for (int i = 1; i <= n; i++) {
		String substr = s.substring(0, i);
		if (dict.contains(substr)) {
			dict.remove(substr);
			if (isComposible(dict, s.substring(i, n)))
				return true;
			dict.add(substr);
		}
	}
	return false;
}

// 下面代码为扩展题,给出一种方案
ArrayList<String> IsComposible(Set<String> dict, String s) {
	ArrayList<String> result = new ArrayList<String>();
	dowork(dict, s, result);
	return result;
}

boolean dowork(Set<String> dict, String s, ArrayList<String> comp) {
	if (s == null || s.length() == 0)
		return true;
	if (dict == null)
		return false;
	
	int n = s.length();
	for (int i = 1; i <= n; i++) {
		String substr = s.substring(0, i);
		if (dict.contains(substr)) {
			dict.remove(substr);
			comp.add(substr);
			if (dowork(dict, s.substrin(i, n), comp))
				return true;
			dict.add(substr);
			comp.removeAt(comp.size() - 1);
		}
	}
	return false;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值