Last active
May 4, 2020 18:29
-
-
Save zeitan/509343b27f077188c22f69367af110da to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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); | |
} | |
} | |
} |
This file contains hidden or 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
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; | |
} |
This file contains hidden or 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
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