题目描述
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".
代码实现
import java.util.*;
/*
dp[i]表示s的第i位能够实现正确截取
dp[j]&&dict.contains(s.substring(j,i))表示字符串s从j到i能够正确截取
通过返回dp数组的最后一位表示该字符串能否正确被截取
*/
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
boolean dp[]=new boolean[s.length()+1];
dp[0]=true;
for(int i=1;i<=s.length();i++){
for(int j=0;j<i;j++){
if(dp[j]&&dict.contains(s.substring(j,i))){
dp[i]=true;
break;
}
}
}
return dp[s.length()];
}
}