-
Notifications
You must be signed in to change notification settings - Fork 0
139. Word Break
Jacky Zhang edited this page Sep 9, 2016
·
1 revision
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".
解题思路为Dynamic Programming。
令can[i]=true表示s.substring(0,i) can be segmented。
can[i] = true if can[j] == true and s.substring(j,i) in wordDict for 0<=j<i
public class Solution {
public boolean wordBreak(String s, Set<String> wordDict) {
if(s == null || wordDict == null) return false;
int len = s.length();
boolean[] can = new boolean[len+1];
can[0] = true;
for(int i = 1; i <= len; i++) {
for(int j = 0; j < i; j++) {
if(can[j] == true && wordDict.contains(s.substring(j, i))) can[i] = true;
}
}
return can[len];
}
}