LeetCode Word Break II

15 篇文章 0 订阅
11 篇文章 0 订阅

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"].

题意:输出能由dict组成S的所有结果集合。

题目链接:https://oj.leetcode.com/problems/word-break-ii/

解法:使用动态规划的思想,stop从最后一个单词出发, start从stop前一个单词出发,开始向前遍历,找出能首位相连并且正好在dict中的单词,将start->stop的值记录下来,然后再从start=0出发,收集所有可能的结果

public List<String> wordBreak(String s, Set<String> dict) {
		// mark记录字符串中所有包含dict中字符的start与stop,其中start的位置是mark的自然序列,stops的位置是list<start>
		// 这些单词有个限制条件,必须能首尾相连
		List<List<Integer>> mark = new ArrayList<List<Integer>>();
		for (int i = 0; i < s.length(); i++) {
			mark.add(new ArrayList<Integer>());
		}
		for (int stop = s.length(); stop > 0; stop--) {
			// 判断必须为首尾相连的单词,如果不是则结束本次循环
			if (stop < s.length() && mark.get(stop).size() == 0)
				continue;
			for (int start = stop - 1; start >= 0; start--) {
				if (dict.contains(s.substring(start, stop))) {
					List<Integer> temp = mark.get(start);
					temp.add(stop);
					mark.set(start, temp);
				}
			}
		}
		ArrayList<String> result = new ArrayList<String>();
		collect(mark, s, 0, new StringBuffer(), result);
		return result;
	}

	// 遍历收集所有可能的字符串
	public void collect(List<List<Integer>> mark, String str, int start,
			StringBuffer hascoll, List<String> result) {
		List<Integer> stops = mark.get(start);
		for (int stop : stops) {
			StringBuffer tempsbuffer = new StringBuffer(hascoll);
			tempsbuffer.append((start == 0 ? "" : " ")
					+ str.substring(start, stop));
			if (stop == str.length()) {
				result.add(tempsbuffer.toString());
				continue;
			}
			collect(mark, str, stop, tempsbuffer, result);
		}
	}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值