diff --git a/src/main/java/org/example/leansoftx/Trie.java b/src/main/java/org/example/leansoftx/Trie.java index 123e15b..965c4d1 100644 --- a/src/main/java/org/example/leansoftx/Trie.java +++ b/src/main/java/org/example/leansoftx/Trie.java @@ -9,6 +9,18 @@ public Trie() { this.root = new TrieNode(); } + // search a word in the trie + public boolean search(String word) { + TrieNode current = root; + for (char c : word.toCharArray()) { + if (!current.hasChild(c)) { + return false; + } + current = current.children.get(c); + } + return current.isEndOfWord; + } + public boolean insert(String word) { TrieNode current = root; for (char c : word.toCharArray()) { @@ -36,7 +48,16 @@ public List autoSuggest(String prefix) { } public List getAllWordsWithPrefix(TrieNode node, String prefix) { - return null; + List words = new ArrayList<>(); + if (node.isEndOfWord) { + words.add(prefix); + } + + for (Map.Entry entry : node.children.entrySet()) { + words.addAll(getAllWordsWithPrefix(entry.getValue(), prefix + entry.getKey())); + } + + return words; } public List getAllWords() { @@ -92,7 +113,7 @@ public List getSpellingSuggestions(String word) { public static int levenshteinDistance(String s, String t) { int m = s.length(); int n = t.length(); - int[][] d = new int[m][n]; + int[][] d = new int[m + 1][n + 1]; if (m == 0) { return n; @@ -113,7 +134,7 @@ public static int levenshteinDistance(String s, String t) { for (int i = 1; i <= m; i++) { for (int j = 1; j <= n; j++) { int cost = (s.charAt(i - 1) == t.charAt(j - 1)) ? 0 : 1; - d[i][j] = Math.min(Math.min(d[i][j] + 1, d[i][j] + 1), d[i][j] + cost); + d[i][j] = Math.min(Math.min(d[i - 1][j] + 1, d[i][j - 1] + 1), d[i - 1][j - 1] + cost); } }