1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| class Solution { public boolean wordBreak(String s, List<String> wordDict) { Set<String> wordSet = new HashSet<>(wordDict); Set<Integer> cannotBreakStartIndexSet = new HashSet<>(); return dfs(s, 0, wordSet, cannotBreakStartIndexSet); }
private boolean dfs(String s, int startIndex, Set<String> wordSet, Set<Integer> cannotBreakStartIndexSet) { if (cannotBreakStartIndexSet.contains(startIndex)) { return false; }
if (startIndex == s.length()) { return true; }
for (int endIndex = startIndex; endIndex < s.length(); endIndex++) { String word = s.substring(startIndex, endIndex + 1); if (wordSet.contains(word)) { if (dfs(s, endIndex + 1, wordSet, cannotBreakStartIndexSet)) { return true; } } }
cannotBreakStartIndexSet.add(startIndex); return false; } }
|