[leetcode] Word Break II

本文深入探讨了编程技术领域的关键知识点,包括但不限于前端开发、后端开发、移动开发、游戏开发、大数据开发等细分技术领域。文章详细介绍了各领域的重要概念、实践技巧和最新发展趋势,旨在为开发者提供全面的技术指导。

https://leetcode.com/problems/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"].

public class Solution {
    private String s;
    private Set<String> dict;
    private int len;
    private LinkedList<String> wds;
    private List<String> sentences;
    private int[][] idxes;// idxes[i][j] means i can reach j
    boolean hasAns = false;
    public List<String> wordBreak(String s, Set<String> wordDict) {
        sentences = new ArrayList<String>();
        if(null == s || "".equals(s)) {
            return sentences;
        }
        
        init(s, wordDict);
        checkReachable0();
        if(hasAns) {
        	find0();
        }
        return sentences;
    }
    
    private void find0() {
    	for(int i=0, n=idxes[0][len]; i<=n; ++i) {
    		int k = idxes[0][i]+1;
    		wds.add(s.substring(0, k));
        	findRest(k);
        	wds.removeLast();
    	}
	}

	private void findRest(int st) {
		if(st == len) {
			addSentence();
			return;
		}
		for(int i=0, n=idxes[st][len]; i<=n; ++i) {
			int k = idxes[st][i] + 1;
			wds.add(s.substring(st, k));
        	findRest(k);
        	wds.removeLast();
		}
	}

	private void checkReachable0() {
        for(int i=0; i<len; ++i) {
            if(dict.contains(s.substring(0, i+1))) {
            	idxes[0][++idxes[0][len]] = i;
                hasAns |= (i+1 == len);
                checkReachable(i+1);
            }
        }		
	}

	private void checkReachable(int st) {
		if(st < len && 0 > idxes[st][len]) {
			for(int i=st; i<len; ++i) {
				if(dict.contains(s.substring(st, i+1))) {
					idxes[st][++idxes[st][len]] = i;
	                hasAns |= (i+1 == len);
	                checkReachable(i+1);
				}
			}
		}
	}

    
	private void addSentence() {
		Iterator<String> it= wds.iterator();
		StringBuilder sb = new StringBuilder();
		if(it.hasNext()) {
			sb.append(it.next());
		}
		while(it.hasNext()) {
			sb.append(" ").append(it.next());
		}
		sentences.add(sb.toString());
	}

	private void init(String s, Set<String> wordDict) {
        this.len = s.length();
        this.s = s;
        this.dict = wordDict;
        this.wds = new LinkedList<String>();
        this.idxes = new int[len][len+1];
        for(int i=0; i<len; ++i) {
        	// -1 means this idx can reach nowhere
        	idxes[i][len] = -1;
        }
    }
}

public class Solution {
	private String s;
	private Set<String> dict;
	private int len;
	private LinkedList<String> wds;
	private List<String> sentences;
	// idxes[i][k]=j: means that i can reach j,k is within[0, count[i]]
	private int[][] idxes;
	// count[i]: the number of word which starts at i and exits in wordDict
	private int[] count;
	boolean hasAns = false;

	public List<String> wordBreak(String s, Set<String> wordDict) {
		sentences = new ArrayList<String>();
		if (null == s || "".equals(s)) {
			return sentences;
		}

		init(s, wordDict);
		checkReachable();
		if (hasAns) {
			find(0);
		}
		return sentences;
	}

	private void find(int st) {
		if (st == len) {
			addSentence();
			return;
		}
		for (int i = 0; i < count[st]; ++i) {
			int k = idxes[st][i] + 1;
			wds.add(s.substring(st, k));
			find(k);
			wds.removeLast();
		}
	}

	/**
	 * 从0开始找,找到所有可能的路径.
	 */
	private void checkReachable() {
		for (int i = 0; i < len; ++i) {
			if (dict.contains(s.substring(0, i + 1))) {
				idxes[0][count[0]++] = i;
				hasAns |= (i + 1 == len);
				checkReachableRest(i + 1);
			}
		}
	}

	private void checkReachableRest(int st) {
		if (st < len && 0 == count[st]) {
			// 遍历过一次的,就全部找到了;所以要有這個條件開著,否則會多次遍歷。
			for (int i = st; i < len; ++i) {
				if (dict.contains(s.substring(st, i + 1))) {
					idxes[st][count[st]++] = i;
					hasAns |= (i + 1 == len);
					checkReachableRest(i + 1);
				}
			}
		}
	}

	private void addSentence() {
		Iterator<String> it = wds.iterator();
		StringBuilder sb = new StringBuilder();
		if (it.hasNext()) {
			sb.append(it.next());
		}
		while (it.hasNext()) {
			sb.append(" ").append(it.next());
		}
		sentences.add(sb.toString());
	}

	private void init(String s, Set<String> wordDict) {
		this.len = s.length();
		this.s = s;
		this.dict = wordDict;
		this.wds = new LinkedList<String>();
		this.idxes = new int[len][len];
		this.count = new int[len];
	}
}

public class Solution {
    private String s;
	private Set<String> dict;
	private int len;
	private LinkedList<String> wds;
	private List<String> sentences;
	// idxes[i][k]=j: means that i can reach j,k is within[0, count[i]]
	private int[][] idxes;
	// count[i]: the number of word which starts at i and exits in wordDict
	private int[] count;
	boolean hasAns = false;

	public List<String> wordBreak(String s, Set<String> wordDict) {
		sentences = new ArrayList<String>();
		if (null == s || "".equals(s)) {
			return sentences;
		}

		init(s, wordDict);
		checkReachable();
		if (hasAns) {
			find(0);
		}
		return sentences;
	}

	private void find(int st) {
		if (st == len) {
			addSentence();
			return;
		}
		for (int i = 0; i < count[st]; ++i) {
			int k = idxes[st][i] + 1;
			wds.add(s.substring(st, k));
			find(k);
			wds.removeLast();
		}
	}

	/**
	 * 从0开始找,找到所有可能的路径.
	 */
	private void checkReachable() {
		Queue<Integer> q = new LinkedList<Integer>();
		q.add(0);
		while (!q.isEmpty()) {
			int st = q.poll();
			hasAns |= (st == len);
			if (st < len && count[st] == 0) {
				// 没有计算过st的count
				for (int i = st; i < len; ++i) {
					if (dict.contains(s.substring(st, i + 1))) {
						q.add(i + 1);
						idxes[st][count[st]++] = i;
					}
				}

			}
		}
	}

	private void addSentence() {
		Iterator<String> it = wds.iterator();
		StringBuilder sb = new StringBuilder();
		if (it.hasNext()) {
			sb.append(it.next());
		}
		while (it.hasNext()) {
			sb.append(" ").append(it.next());
		}
		sentences.add(sb.toString());
	}

	private void init(String s, Set<String> wordDict) {
		this.len = s.length();
		this.s = s;
		this.dict = wordDict;
		this.wds = new LinkedList<String>();
		this.idxes = new int[len][len];
		this.count = new int[len];
	}

}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值