提高树的效率

时间:2019-03-16 19:22:54

标签: prefix-tree multiway-tree

我刚开始学习高级数据结构,这是我第一次实现Trie。我试图实现一个支持插入,删除和更新的特里。但是,我找不到将oldStrings更新为newStrings的有效方法。我只能删除(oldString)和插入(newString)。

有没有有效的方法可以做到这一点?

这是TrieNode类

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

class TrieNode{
    private Map<Character, TrieNode> children;
    private boolean wordBreak;
    private int count;

    TrieNode(){
        this.children = new HashMap<>();
        this.wordBreak = false;
        this.count = 0;
    }

    public Map<Character, TrieNode> getChildren() {
        return children;
    }

    public boolean isWordBreak() {
        return wordBreak;
    }

    public void setWordBreak(boolean wordBreak) {
        this.wordBreak = wordBreak;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }
}

这是Trie类

public class Trie{
    private final TrieNode root;

    Trie(){
        root = new TrieNode();
    }

    public void insert(String word){
        TrieNode current = root;
        for(char c : word.toCharArray()){
            TrieNode node = current.getChildren().get(c);
            if(node == null) {
                node = new TrieNode();
                current.getChildren().put(c, node);
            }
            current = node;
        }
        current.setWordBreak(true);
        current.setCount(current.getCount() + 1);
    }

    public void update(String oldWord, String newWord){
        delete(oldWord);
        insert(newWord);
    }

    public int query(String word){
        TrieNode current = root;
        for(char c : word.toCharArray()){
            TrieNode node = current.getChildren().get(c);
            if(node == null)
                return 0;
            current = node;
        }
        return current.isWordBreak() ? current.getCount() : 0;
    }

    private boolean delete(TrieNode current, String word, int index){
        if(index == word.length()){
            if(!current.isWordBreak())
                return false;
            current.setWordBreak(false);
            current.setCount(current.getCount() - 1);
            return current.getChildren().size() == 0;
        }
        char c = word.charAt(index);
        TrieNode node = current.getChildren().get(c);
        if(node == null)
            return false;
        boolean isSafeToDelete = delete(node, word, index + 1);
        if(isSafeToDelete){
            current.getChildren().remove(c);
            current.setCount(current.getCount() - 1);
            return current.getChildren().size() == 0;
        }
        return false;
    }

    public void delete(String word){
        delete(root, word, 0);
    }

0 个答案:

没有答案