字典树

2020-08-06  本文已影响0人  不再_犹豫
class Tree{
    class Node {
        public int[] ch = new int[26];
    }
    public List<Node> tree = new ArrayList<Node>();
    public void insertWord(String s){
        int len = s.length(),add = 0;
        for(int i = 0;i < len;i++){
            int x = s.charAt(i) - 'a';
            if(tree.get(add).ch[x] == 0){
                tree.add(new Node());
                tree.get(add).ch[x] = tree.size() - 1;
            }
            add = tree.get(add).ch[x];
        }
    }
    public boolean findWord(String s){
        int add = 0;
        for(int i = 0;i < s.length();i++){
            int x = s.charAt(i) - 'a';
            if(tree.get(add).ch[x] == 0) return false;
            add = tree.get(add).ch[x];
        }
        return true;
    }
    public Tree(){
        tree.add(new Node());
    }
}
上一篇下一篇

猜你喜欢

热点阅读