Skip to content

Java Chapter 12: Tries #67

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Feb 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions java/Tries/DesignATrie.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import java.util.HashMap;
import java.util.Map;

class TrieNode {
Map<Character, TrieNode> children;
boolean isWord;
public TrieNode() {
this.children = new HashMap<>();
this.isWord = false;
}
}

public class DesignATrie {
TrieNode root;

public DesignATrie() {
this.root = new TrieNode();
}

public void insert(String word) {
TrieNode node = this.root;
for (char c : word.toCharArray()) {
// For each character in the word, if it's not a child of
// the current node, create a new TrieNode for that
// character.
node.children.putIfAbsent(c, new TrieNode());
node = node.children.get(c);
}
// Mark the last node as the end of a word.
node.isWord = true;
}

public boolean search(String word) {
TrieNode node = this.root;
for (char c : word.toCharArray()) {
// For each character in the word, if it's not a child of
// the current node, the word doesn't exist in the Trie.
if (!node.children.containsKey(c)) {
return false;
}
node = node.children.get(c);
}
// Return whether the current node is marked as the end of the
// word.
return node.isWord;
}

public boolean hasPrefix(String prefix) {
TrieNode node = this.root;
for (char c : prefix.toCharArray()) {
if (!node.children.containsKey(c)) {
return false;
}
node = node.children.get(c);
}
// Once we've traversed the nodes corresponding to each
// character in the prefix, return True.
return true;
}
}
69 changes: 69 additions & 0 deletions java/Tries/FindAllWordsOnABoard.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class TrieNode {
Map<Character, TrieNode> children;
String word;
public TrieNode() {
this.children = new HashMap<>();
this.word = null;
}
}

public class FindAllWordsOnABoard {
public List<String> findAllWordsOnABoard(char[][] board, String[] words) {
TrieNode root = new TrieNode();
// Insert every word into the trie.
for (String word : words) {
TrieNode node = root;
for (char c : word.toCharArray()) {
node.children.putIfAbsent(c, new TrieNode());
node = node.children.get(c);
}
node.word = word;
}
List<String> res = new ArrayList<>();
// Start a DFS call from each cell of the board that contains a
// child of the root node, which represents the first letter of a
// word in the trie.
for (int r = 0; r < board.length; r++) {
for (int c = 0; c < board[0].length; c++) {
if (root.children.containsKey(board[r][c])) {
dfs(board, r, c, root.children.get(board[r][c]), res);
}
}
}
return res;
}

private void dfs(char[][] board, int r, int c, TrieNode node, List<String> res) {
// If the current node represents the end of a word, add the word to
// the result.
if (node.word != null) {
res.add(node.word);
// Ensure the current word is only added once.
node.word = null;
}
char temp = board[r][c];
// Mark the current cell as visited.
board[r][c] = '#';
// Explore all adjacent cells that correspond with a child of the
// current TrieNode.
int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
for (int[] d : dirs) {
int nextR = r + d[0];
int nextC = c + d[1];
if (isWithinBounds(nextR, nextC, board) && node.children.containsKey(board[nextR][nextC])) {
dfs(board, nextR, nextC, node.children.get(board[nextR][nextC]), res);
}
}
// Backtrack by reverting the cell back to its original character.
board[r][c] = temp;
}

private boolean isWithinBounds(int r, int c, char[][] board) {
return 0 <= r && r < board.length && 0 <= c && c < board[0].length;
}
}
57 changes: 57 additions & 0 deletions java/Tries/InsertAndSearchWordsWithWildcards.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import java.util.HashMap;
import java.util.Map;

class TrieNode {
Map<Character, TrieNode> children;
boolean isWord;
public TrieNode() {
this.children = new HashMap<>();
this.isWord = false;
}
}

public class InsertAndSearchWordsWithWildcards {
TrieNode root;

public InsertAndSearchWordsWithWildcards() {
this.root = new TrieNode();
}

public void insert(String word) {
TrieNode node = this.root;
for (char c : word.toCharArray()) {
node.children.putIfAbsent(c, new TrieNode());
node = node.children.get(c);
}
node.isWord = true;
}

public boolean search(String word) {
// Start searching from the root of the trie.
return searchHelper(0, word, this.root);
}

private boolean searchHelper(int wordIndex, String word, TrieNode node) {
for (int i = wordIndex; i < word.length(); i++) {
char c = word.charAt(i);
// If a wildcard character is encountered, recursively
// search for the rest of the word from each child node.
if (c == '.') {
for (TrieNode child : node.children.values()) {
// If a match is found, return true.
if (searchHelper(i + 1, word, child)) {
return true;
}
}
return false;
} else if (node.children.containsKey(c)) {
node = node.children.get(c);
} else {
return false;
}
}
// After processing the last character, return true if we've
// reached the end of a word.
return node.isWord;
}
}