版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chengyunyi123/article/details/76919012
题目描述
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”.
时间限制:1秒 空间限制:32768K
这题典型的动态规划
import java.util.Set;
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
int len = s.length();
// dp[i]表示0到i位可分
boolean[] dp = new boolean [len+1];
dp[0] = true; //0到0可分
for(int i = 1; i <= len; i ++){
for(int j = 0; j < len; j ++){
//如果 0-j可分,并且dic中包含j-i 的子串,那么0-i 为可分
if(dp[j] && dict.contains(s.substring(j,i))){
dp[i] = true;
}
}
}
return dp[len];
}
}