Am a beginner learner. Need help on Trie implementation for longest common prefix.
Single character and single word test cases are failing
For example: {“a”}
Have written the following code which works fine locally with the failed test case on LeetCode
Please tell if you find any logical errors
“
class Solution {
static class Node {
Node[] children;
int childCount;
boolean eow;
Node(){
children = new Node[26];
for (int i = 0; i < 26; i++){
children[i] = null;
}
eow = false;
}
}
static void insertNode(String str){
Node current = root;
for (int i = 0; i < str.length(); i++){
int index = str.charAt(i)-'a';
if (current.children[index] == null){
current.children[index] = new Node();
current.childCount++;
}
if (i == str.length()-1){
current.children[index].eow = true;
}
current = current.children[index];
}
}
static String longestCommonPrefix() {
Node current = root;
String prefix = "";
if (current.childCount == 0)
return "";
while (current.childCount == 1) {
for (int i =0; i < 26; i++) {
if (current.children[i] != null){
prefix += (char)(i+'a');
current = current.children[i];
break;
}
}
}
return prefix;
}
static Node root = new Node();
public static void main(String[] strs) {
strs = new String[]{"a"};
for (String s : strs) {
insertNode(s);
}
System.out.println(longestCommonPrefix());
}
}
“
Tried to implement Trie to solve Longest Common Prefix Problem on LeetCode but am failing single character input case -> {“a”}
Works fine locally.