139.WordBreak

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".

 

public boolean wordBreak(String s, List<String> wordDict) {
boolean[] f = new boolean[s.length() + 1];
f[0] = true;
for(int i = 0; i < s.length(); i++) {
for(int j = i; j < s.length(); j++) {
if(f[i] && wordDict.contains(s.substring(i, j + 1))){
f[j + 1] = true;
}
}
}
return f[s.length()];
}
posted @ 2022-11-20 16:22  MarkLeeBYR  阅读(19)  评论(0)    收藏  举报