Skip to content

Instantly share code, notes, and snippets.

@maxmalakhov
Created March 17, 2023 08:24
Show Gist options
  • Save maxmalakhov/5797ad985e0c1cd83559d413dd638c06 to your computer and use it in GitHub Desktop.
Save maxmalakhov/5797ad985e0c1cd83559d413dd638c06 to your computer and use it in GitHub Desktop.
LeetCode 'Trie'
public class Trie {
private static final char[] KEYS = "abcdefghijklmnopqrstuvwxyz".toCharArray();
private Map<Character, List<String>> data = new HashMap<>(KEYS.length);
public Trie() {
// init data
for(Character key: KEYS) {
data.put(key, new ArrayList<>());
}
}
public void insert(String word) {
List<String> bucket = data.get(word.charAt(0));
bucket.add(word);
}
public boolean search(String word) {
List<String> bucket = data.get(word.charAt(0));
return bucket.contains(word);
}
public boolean startsWith(String prefix) {
List<String> bucket = data.get(prefix.charAt(0));
return bucket.stream().anyMatch(str -> str.startsWith(prefix));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment