Word Break

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

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

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

DP, 我的最爱。

public class Solution {
    public boolean wordBreak(String s, Set<String> dict) {
        int len = s.length();
		boolean [] map = new boolean[len];
		for (int i = 0; i < len; i++) {
			if (dict.contains(s.substring(0, i + 1))) {
				map[i] = true;
			}
		}
		for (int i = 1; i < len; i++) {
			for (int j = i; j < len; j++) {
				map[j] = map[j] | (dict.contains(s.substring(i, j + 1)) & map[i - 1]);
			}
		}
		return map[len - 1];
    }
}


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