|
| 1 | +import java.util.List; |
| 2 | + |
| 3 | +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 | + 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; |
| 53 | + } |
| 54 | + } |
| 55 | + |
| 56 | + return false; |
| 57 | + } |
| 58 | +} |
0 commit comments