Javaで接尾辞トライを実装しようとしています。トライにはルートノードがあり、トライにはエッジが接続されています。しかし、constructTrie(T)
(文字列Tを与えられたtrieを構築する)やsubstring(S,T)
(SがTの部分文字列かどうかを調べる)のような関数を実装するときは、現在検討中のノードcNode
を検討しています。Javaでのオブジェクト参照の変更
cNode
の値を正しく変更しているかどうかわかりません。以下はクラスTrie
です。
import java.util.*;
class Trie{
protected Node root = null;
public Trie(){
Node n = new Node();
root = n;
}
// Constructs a trie for a given string T
public void constructTrie(String T){
ArrayList<String> suffixArray = new ArrayList<String>();
T += "#"; // Terminator
int length = T.length();
// Creates suffix array and removes first letter with every iteration
for(int i=0; i<length; i++){
suffixArray.add(T);
T = T.substring(1);
}
// Goes through suffix array
for(int i=0; i<length; i++){
Node cNode = null;
cNode = root; // Current node
int j = 0;
// Goes through each letter of an entry in the suffix array
while(j < (suffixArray.get(i)).length()){
int index = cNode.findEdge((suffixArray.get(i)).charAt(j));
// If an edge is found at the root with the current letter, update cNode and remove the letter from word
if(index != -1){
cNode = cNode.getEdge(index).getNode(); // Gets node pointed at by edge and sets it as current node
String replace = (suffixArray.get(i)).substring(1);
suffixArray.set(0, replace); // Erases first letter of suffix
j++;
System.out.println(i + " " + j + " " + replace);
}
// If an edge is not found at the root, write the whole word
else{
for(int k=0; k<(suffixArray.get(i)).length(); k++){
Edge e = new Edge((suffixArray.get(i)).charAt(k)); // Creates edge with current letter of current entry of the suffix array
Node n = new Node(); // Creates node to be pointed at by edge
e.setNode(n);
cNode.newEdge(e);
cNode = n; // Updates current node
}
j = (suffixArray.get(i)).length(); // If the word is written, we break from the while and move on to the next suffix array entry
}
}
}
}
// Checks if S is a substring of T
public boolean substring(String S, String T){
constructTrie(T);
Node cNode = null;
cNode = root;
int index;
for(int i=0; i<S.length(); i++){
index = cNode.findEdge(S.charAt(i));
if(index == -1)
return false; // Substring was not found because a path was not followed
cNode = (cNode.getEdge(index)).getNode(); // Reset current node to the next node in the path
}
return true; // Substring was found
}
具体的には、Iタイプトライのオブジェクトが作成されるときroot
を初期化、クラス変数としてNode root = null
を設定し、方法に示すようにcNode
を変化させてい?コードはエラーなしでコンパイルされますが、テスト時に必ずしも正しい応答を出力するとは限りません。テストされると、 'es'は 'pest'の部分文字列ではないことを出力します。
「トライ」を「ツリー」に置き換えると、回答が多分得られるかもしれません。 – Mena
@Mena実際には、最初にトライを実装し、その性能を最適化するためにツリーに変更する必要があります。 –
私は実際にはツリーだけでなく、[Trie](https://en.wikipedia.org/wiki/Trie)であることを期待しています。 – azurefrog