|
| 1 | +// https://leetcode.com/problems/word-break |
| 2 | +// T: O(s^3 + w) |
| 3 | +// S: O(s + w) |
| 4 | + |
| 5 | +import java.util.HashSet; |
1 | 6 | import java.util.List;
|
| 7 | +import java.util.Set; |
2 | 8 |
|
3 | 9 | public class WordBreak {
|
4 |
| - private static final class Trie { |
5 |
| - private static final int LETTERS_IN_ENGLISH_ALPHABET = 26; |
6 |
| - |
7 |
| - Trie[] letters = new Trie[LETTERS_IN_ENGLISH_ALPHABET]; |
8 |
| - boolean isWord = false; |
9 |
| - |
10 |
| - public void insert(String word) { |
11 |
| - insert(word, 0, this); |
12 |
| - } |
13 |
| - |
14 |
| - private void insert(String s, int index, Trie root) { |
15 |
| - if (index >= s.length()) { |
16 |
| - root.isWord = true; |
17 |
| - return; |
18 |
| - } |
19 |
| - if (root.letters[s.charAt(index) - 'a'] == null) { |
20 |
| - root.letters[s.charAt(index) - 'a'] = new Trie(); |
21 |
| - } |
22 |
| - insert(s, index + 1, root.letters[s.charAt(index) - 'a']); |
23 |
| - } |
24 |
| - |
25 |
| - public boolean exists(String word) { |
26 |
| - return exists(word, 0, this); |
27 |
| - } |
28 |
| - |
29 |
| - private boolean exists(String s, int index, Trie root) { |
30 |
| - if (index >= s.length()) { |
31 |
| - return root.isWord; |
32 |
| - } |
33 |
| - if (root.letters[s.charAt(index) - 'a'] == null) return false; |
34 |
| - return exists(s, index + 1, root.letters[s.charAt(index) - 'a']); |
35 |
| - } |
36 |
| - } |
37 |
| - |
38 |
| - |
39 | 10 | public boolean wordBreak(String s, List<String> wordDict) {
|
40 |
| - final Trie trie = new Trie(); |
41 |
| - for (String string : wordDict) { |
42 |
| - trie.insert(string); |
43 |
| - } |
44 |
| - return wordBreak(s, trie); |
45 |
| - } |
46 |
| - |
47 |
| - private boolean wordBreak(String s, Trie root) { |
48 |
| - if (s.isEmpty()) return true; |
49 |
| - |
50 |
| - for (int i = 0 ; i < s.length() ; i++) { |
51 |
| - if (root.exists(s.substring(0, i + 1)) && wordBreak(s.substring(i + 1), root)) { |
52 |
| - return true; |
| 11 | + final Set<String> words = new HashSet<>(wordDict); |
| 12 | + final boolean[] dp = new boolean[s.length() + 1]; |
| 13 | + dp[0] = true; |
| 14 | + |
| 15 | + for (int i = 1 ; i <= s.length() ; i++) { |
| 16 | + for (int j = 0 ; j < i ; j++) { |
| 17 | + if (dp[j] && words.contains(s.substring(j, i))) { |
| 18 | + dp[i] = true; |
| 19 | + break; |
| 20 | + } |
53 | 21 | }
|
54 | 22 | }
|
55 | 23 |
|
56 |
| - return false; |
| 24 | + return dp[dp.length - 1]; |
57 | 25 | }
|
58 | 26 | }
|
0 commit comments