Created
August 20, 2021 06:27
-
-
Save kylelong/a3c6443a1aa3dfacc780e9b67e5f3821 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
package com.company; | |
import java.util.*; | |
public class Trie { | |
public static void main(String[] args) { | |
// String s = "tttt"; | |
Trie t = new Trie(); | |
// t.insert(s); | |
// t.insert("ttt"); | |
// System.out.println(t.startsWith("tt")); | |
String [] a = {"one", "two", "three"}; | |
List<String> list = Arrays.asList(a); | |
String [] b = {"onetwo", "two"}; | |
for(String s: a){ | |
t.insert(s); | |
} | |
for(String s: b){ | |
HashMap<String, Integer> map = new HashMap<>(); | |
// return false if | |
for(String word: a){ | |
int index = s.indexOf((word)); | |
if(index > -1){ | |
map.put(word, index); | |
} | |
} | |
Set<String> keys = map.keySet(); // | |
} | |
} | |
class Node { | |
Node[] children = new Node[26]; | |
boolean isCompleted; | |
} | |
private Node root; | |
public Trie() { | |
root = new Node(); | |
} | |
public void insert(String s) { | |
Node node = root; | |
for (int i = 0; i < s.length(); i++) { | |
char c = s.charAt(i); | |
if (node.children[c - 'a'] == null) { | |
node.children[c - 'a'] = new Node(); | |
} | |
node = node.children[c - 'a']; // moves pointer down. | |
} | |
node.isCompleted = true; | |
} | |
public boolean search(String word) { | |
Node node = searchNode(word); | |
if (node == null) { | |
return false; | |
} | |
return node.isCompleted; | |
} | |
public boolean startsWith(String prefix) { | |
Node node = searchNode(prefix); | |
if (node == null) { | |
return false; | |
} | |
return true; | |
} | |
public Node searchNode(String s) { | |
Node node = root; | |
for (int i = 0; i < s.length(); i++) { | |
char c = s.charAt(i); | |
if (node.children[c - 'a'] == null) { | |
return null; | |
} else { | |
node = node.children[c - 'a']; | |
} | |
} | |
return node; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment