// 当前 i 个字符组成的字符串可以由单词组成时,计算前 j 个字符组成的字符串的状态 for (inti=0; i <= word.length(); i++) { if (dp[i] == -1) { // 当前 i 个字符组成的字符串不能由单词组成时,此时不能递推,注意此处为 continue, 即后续的 i 依然要进行计算,此条件也不能归入到 for 循环的判断逻辑中,否则语义将变为 break continue; }
longhash=0; // 当前 i 个字符可以由单词组成时,计算前 j 个字符组成的字符串的状态 for (intj= i + 1; j <= word.length(); j++) { hash = hash * PRIME + word.charAt(j - 1); // 注意索引下标 if (wordHashSet.contains(hash)) { dp[j] = Math.max(dp[j], dp[i] + 1); } }
if (dp[word.length()] > 1) { returntrue; } }
returnfalse; }
privatelonghash(String word) { longhash=0; for (inti=0; i < word.length(); i++) { hash = hash * PRIME + word.charAt(i); } return hash; } }