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"
.
思路:
运用动态规划法,将问题分解为最优子结构。
定义t[i] 为s字符串上[0,i]的子串是否可以被segmented by dictionary.
那么
t[i] = true if s[0,i]在dictionary里面
= true if s[k] == true 并且 s[k+1,i]在dictionary里面, 0<k<i
= false if no such k exist.
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
boolean[] t = new boolean[s.length() + 1];
t[0] = true; //set the start status
for (int i = 0; i < s.length(); i++) {
if (!t[i]) {
continue;
}
for (String word: dict) {
int len = word.length();
int end = len + i;
if (end > s.length()) continue;
if (t[end]) continue;
if (s.substring(i, end).equals(word)) {
t[end] = true;
}
}
}
return t[s.length()];
}
}