Problem: 139. 单词拆分
题目描述
思路
1.定义状态:Boolean数组dp[i]长度为s.lenght + 1,表示子串s[0: i - 1]是否能拆分成单词表中的单词;
2.状态的初始化:令dp[0]为true;(此处可以理解只是便于后续继续用上状态转移方程);
3.状态转移:我们先将wordDict中的单词字符串添加到一个set集合中,再利用双循环,分割字符串(看代码中的操作),得到前缀部分s[0: j-1]和后缀部分s[j: i],若后缀部分是单词且前缀部分的dp[j]为true则将dp[i]设为true并退出当前循环;最终返回dp[s.length]
复杂度
时间复杂度:
O ( n 2 ) O(n^2) O(n2)其中 n n n为字符串s的长度
空间复杂度:
O ( n ) O(n) O(n)
Code
class Solution {
/**
* Word Break(Dynamic programing)
*
* @param s Given string
* @param wordDict A dictionary of strings
* @return boolean
*/
public boolean wordBreak(String s, List<String> wordDict) {
Set<String> wordSet = new HashSet<>(wordDict);
int len = s.length();
boolean[] dp = new boolean[len + 1];
dp[0] = true;
for (int i = 1; i <= len; ++i) {
for (int j = i - 1; j >= 0; --j) {
String suffix = s.substring(j, i);
if (wordSet.contains(suffix) && dp[j]) {
dp[i] = true;
break;
}
}
}
return dp[len];
}
}