139. Word Break

Description

Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words.

For example, given
s = "leetcode",
dict = ["leet", "code"].

Return true because "leetcode" can be segmented as "leet code".

UPDATE (2017/1/4):
The wordDict parameter had been changed to a list of strings (instead of a set of strings). Please reload the code definition to get the latest changes.

Solution

DP, time O(n * n * dictSize)

这道题用recursive解法会TLE,必须上DP啦。另外真是不懂wordDict为什么不是Set……

class Solution {
    public boolean wordBreak(String s, List wordDict) {
        if (s == null || s.isEmpty()) {
            return false;
        }
        
        int n = s.length();
        boolean[] canBreak = new boolean[n + 1];    // s.substring(0, i) can break or not
        canBreak[0] = true;
        
        for (int i = 0; i < n; ++i) {
            for (int j = i; j >= 0; --j) {
                if (search(wordDict, s.substring(j, i + 1)) && canBreak[j]) {
                    canBreak[i + 1] = true;
                    break;
                }
            }
        }
        
        return canBreak[n];
    }
    
    public boolean search(List dict, String s) {
        for (String word : dict) {
            if (word.equals(s)) {
                return true;
            }
        }
        
        return false;
    }
}

你可能感兴趣的:(139. Word Break)