Skip to content

Instantly share code, notes, and snippets.

@zeitan
Last active May 4, 2020 18:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeitan/509343b27f077188c22f69367af110da to your computer and use it in GitHub Desktop.
Save zeitan/509343b27f077188c22f69367af110da to your computer and use it in GitHub Desktop.
preOrder(Trie curr, List<String> sortedWords)
{
if (curr == null || sortedWords.size() == 3 ) {
return;
}
for (int i = 0; i < 26; i++)
{
if (curr.character[i] != null)
{
if (curr.character[i].key != null) {
sortedWords.add(curr.character[i].key);
}
preOrder(curr.character[i], sortedWords);
}
}
}
List<List<String>> suggestedSearchWord(String[] products, String searchWord) {
List<List<String>> suggests = new ArrayList<>();
Trie root = new Trie();
for (String product : products) {
root.insert(root, product);
}
Trie curr = root;
for (int i = 0; i < searchWord.length(); i++) {
if (curr != null) {
curr = curr.search(String.valueOf(searchWord.charAt(i)));
List<String> sortedWords = new ArrayList<>();
if (curr != null && curr.key != null)
sortedWords.add(curr.key);
preOrder(curr, sortedWords);
suggests.add(sortedWords);
}
else
break;
}
return suggests;
}
class Trie {
String key;
Trie[] character = null;
// Constructor
Trie()
{
// Trie supports lowercase English characters (a - z)
// so character size is 26
character = new Trie[26];
}
public void insert(Trie head, String str)
{
// start from root node
Trie curr = head;
for (int i = 0; i < str.length(); i++)
{
// create a new node if path doesn't exists
if (curr.character[str.charAt(i) - 'a'] == null) {
curr.character[str.charAt(i) - 'a'] = new Trie();
}
// go to next node
curr = curr.character[str.charAt(i) - 'a'];
}
// store key in leaf node
curr.key = str;
}
public Trie search(String key) {
return character[key.charAt(0) - 'a'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment