LeetCode | Word Break II

题目

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

分析

直接的思路就是用动态规划,实现中要注意:

1. 需要加上备忘录,避免超时;

2. 需要判断句子是否能正确分割,下述代码中,利用null来标识不能分割的子句;

3. 下述代码中,没有在意空间,备忘录中直接纪录了各个子句的字符串分割结果;如果空间上有所限制的话,可以在备忘录中纪录分割点的索引,最后再生成结果;

4. 进一步提升性能的话,可以左右同时开工,建立二维的备忘录。

代码

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class WordBreakII {
	private Map<Integer, ArrayList<String>> records = new HashMap<Integer, ArrayList<String>>();
	private Set<String> dict = null;
	private String s = null;
	private int N = 0;

	public ArrayList<String> wordBreak(String s, Set<String> dict) {
		// Note: The Solution object is instantiated only once and is reused by
		// each test case.
		if (s == null || s.length() <= 0 || dict == null || dict.size() <= 0) {
			return new ArrayList<String>();
		}
		records.clear();
		this.dict = dict;
		this.s = s;
		N = s.length();

		ArrayList<String> list = solve(0);
		if (list == null) {
			list = new ArrayList<String>();
		}
		return list;
	}

	private ArrayList<String> solve(int i) {
		if (records.containsKey(i)) {
			return records.get(i);
		}

		ArrayList<String> list = new ArrayList<String>();
		if (i >= N) {
			records.put(i, list);
			return list;
		}
		for (int j = i + 1; j <= N; ++j) {
			String word = s.substring(i, j);
			if (dict.contains(word)) {
				ArrayList<String> subList = solve(j);
				ArrayList<String> newList = new ArrayList<String>();
				if (subList == null) {
					continue;
				} else if (subList.size() == 0) {
					newList.add(word);
				} else {
					for (String result : subList) {
						newList.add(word + " " + result);
					}
				}
				list.addAll(newList);
			}
		}
		if (list.size() == 0) {
			list = null;
		}
		records.put(i, list);
		return list;
	}
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值