데이터 구조 와 알고리즘 - Trie 트 리
                                            
 6172 단어  데이터 구조데이터 구조 와 알고리즘
                    
콘 셉 트
접두사 트 리, 사전 트 리, 단어 찾기 트 리 나 키 트 리 라 고도 합 니 다.나무 구조, 해시 나무의 변종.트 리 의 경로 에 저 장 된 것 은 문자 이 고 노드 에 저 장 된 것 은 현재 노드 를 마지막 으로 하 는 문자열 의 개수 입 니 다.
성질:
전형 적 인 응용
장점.
공간 교환.문자열 의 공공 접 두 사 를 이용 하여 조회 시간의 비용 을 낮 추어 효율 을 높이 는 목적 을 달성 하 다.
사고의 방향 을 세우다.
모든 노드 가 문자 라면 모든 노드 는 26 개의 자모 와 연 결 될 수 있 습 니 다. 이 를 위해 모든 노드 에 경로 의 노드 와 끝 노드, 그리고 연결 배열 을 기록 해 야 합 니 다.
응용 문제
1、208. Implement Trie (Prefix Tree)
Implement a trie with
insert ,  search , and  startsWith  methods. Example:
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // returns true
trie.search("app");     // returns false
trie.startsWith("app"); // returns true
trie.insert("app");   
trie.search("app");     // returns true
  Note:
a-z . class Trie {
    
    public class Node{
        int path; //             
        int end;  //              
        Node[] nexts;  //                
        
        public Node(){
            path = 0;
            end = 0;
            nexts = new Node[26];
        }
    }
    
    private Node node;
    /** Initialize your data structure here. */
    public Trie() {
        node = new Node();
    }
    
    /** Inserts a word into the trie. */
    public void insert(String word) {
        if(word == null)
            return;
        char[] str = word.toCharArray();
        Node root = node;
        int index = 0;
        for(int i = 0; i < str.length; i++){
            index = str[i] - 'a';
            if(root.nexts[index] == null)
                root.nexts[index] = new Node();
            root.path++;
            root = root.nexts[index];
        }
        root.end++;
    }
    
    /** Returns if the word is in the trie. */
    public boolean search(String word) {
        if(word == null)
            return false;
        char[] str = word.toCharArray();
        Node root = node;
        int index = 0;
        for(int i = 0; i < str.length; i++){
            index = str[i] - 'a';
            if(root.nexts[index] == null)
                return false;
             root = root.nexts[index];
        }
        return root.end == 0 ? false : true;
    }
    
    /** Returns if there is any word in the trie that starts with the given prefix. */
    public boolean startsWith(String prefix) {
        if(prefix == null)
            return false;
        char[] str = prefix.toCharArray();
        Node root = node;
        int index = 0;
        for(int i = 0; i < str.length; i++){
            index = str[i] - 'a';
            if(root.nexts[index] == null)
                return false;
            root = root.nexts[index];
        }
        return true;
    }
}
  211. Add and Search Word - Data structure design
Design a data structure that supports the following two operations:
void addWord(word)
bool search(word)
  search(word) can search a literal word or a regular expression string containing only letters
a-z  or  . . A  .  means it can represent any one letter. Example:
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true
  Note: You may assume that all words are consist of lowercase letters
a-z . class WordDictionary{
    
    private Node root;
    public WordDictionary() {
        root = new Node((char) 0);
    }
    
    //*** Create Trie tree
    public void addWord(String word) {
        Node node = root;
        char[] arr = word.toCharArray();
        for(char ch : arr){
            Node child = node.children.get(ch);
            if(child == null){
                child = new Node(ch);
                node.children.put(ch, child);
            }
            node = child;
        }
    
        //*** Mark the end ot the worn in tree
        node.children.put(null, null);
    }
    
    public boolean search(String word) {
        char[] arr = word.toCharArray();
        return search(arr, 0, root);
    }
    
    //*** Recursive method to find word in the Trie tree
    private boolean search(char[] arr, int pos, Node node){
        
        //*** False -> if this is not the end of the word in the tree
        if(node == null || node.children == null)
            return false;
        if(pos == arr.length)
            return node.children.containsKey(null);
        
        //*** If it's a point -> find all possibilities
        if(arr[pos] == '.'){
            for(Character ch : node.children.keySet()){
                if(search(arr, pos+1, node.children.get(ch)))
                    return true;
            }
            return false;
        } else {
            
            //*** If it's not a point -> find the next character
            return search(arr, pos+1, node.children.get(arr[pos]));
        }
    }
    
    private class Node {
        char ch;
        Map children;
        public Node(char ch){
            this.ch = ch;
            children = new HashMap<>();
        }
    }
}   이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
정수 반전Udemy 에서 공부 한 것을 중얼거린다 Chapter3【Integer Reversal】 (예) 문자열로 숫자를 반전 (toString, split, reverse, join) 인수의 수치 (n)가 0보다 위 또는 ...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.