题目大意:给定一个字符串s和一个字典dict,判断该字符串是否可以由字典中的单词组成。https://oj.leetcode.com/problems/word-break/
分析:这是一道动态规划题,动态规划题的基本思路是首先判断要存储哪些历史信息和用什么数据结构存储,其次是最重要的递推关系,即如何由历史信息得出当前步的结果,最后就是需要考虑起始条件的值。
1. 存储的历史信息是his[i],表示到字符串s的第i个字符为止能不能用字典中的词表示,是一个Boolean型的数组;
2. 对于当前字符i,如果它前面的字符his[0,...,i-1]都在字典中,且到第i个字符的串都在字典中,则his[i]为true;
3. 起始条件his[0] = true。
Java实现:
public class Solution {
public boolean wordBreak(String s, Set<String> dict) {
if(s == null || s.length() == 0) return true;
int len = s.length();
boolean[] his = new boolean[len + 1];
his[0] = true;
for(int i = 0; i < len; i ++) {
StringBuilder sb = new StringBuilder(s.substring(0, i+1));
for(int j = 0; j <= i; j ++) {
if(his[j] && dict.contains(sb.toString())) {
his[i + 1] = true;
break;
}
sb.deleteCharAt(0);
}
}
return his[len];
}
}