Word Break

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

Example

Given s = "lintcode", dict = ["lint", "code"].

Return true because “lintcode” can be break as "lint code".

Version 1. DP 常规做法 无优化 straight forward

    public boolean wordSegmentation(String s, Set < String > dict) {
    	if (s == null || dict == null) {
    		return false;
    	}
    	//result[i] means if s.subString(0,i+1) can be break.
    	boolean[] result = new boolean[s.length() + 1];
    	result[0] = true;
    	for (int i = 0; i < s.length(); i++) {
    		if (dict.contains(s.substring(0, i + 1))) {
    			result[i + 1] = true;
    		} else {
    			for (int j = 0; j < i; j++) {
    				if (result[j + 1] && dict.contains(s.substring(j + 1, i + 1))) {
    					result[i + 1] = true;
    					break;
    				}
    			}
    		}
    	}
    	return result[s.length()];
    }

Version 2. DP 优化 根据字典里词的长度 减少查询次数

FacebookTwitterGoogle+Share

Leave a Reply

Your email address will not be published. Required fields are marked *