Напишите функцию, которая найдет самую длинную строку общего префикса среди массива строк. .
Если общего префикса нет, верните пустую строку "".
Пример 1:
Ввод: strs = ["flower","flow","flight"]
Вывод: "fl"
Я подошел к этому с помощью Trie со следующим кодом:
Код: Выделить всё
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());
}
}
Например: {"a"
В чем ошибка?
Подробнее здесь: https://stackoverflow.com/questions/786 ... n-leetcode