Created
March 17, 2023 08:24
-
-
Save maxmalakhov/5797ad985e0c1cd83559d413dd638c06 to your computer and use it in GitHub Desktop.
LeetCode 'Trie'
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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