【LeetCode每日一题】前缀树

前缀树

一、题目描述

Trie(发音相似 "try")或者说 前缀树 是一种树形数据结构,用于高效地存储和检索字符串数据集中的键。这一数据结构有至关多的应用情景,例如自动补完和拼写检查。

请你实现 Trie 类:

	一、Trie() 初始化前缀树对象。
	二、void insert(String word) 向前缀树中插入字符串 word 。
	三、boolean search(String word) 若是字符串 word 在前缀树中,返回 true(即,在检索以前已经插入);不然,返回 false 。
	四、boolean startsWith(String prefix) 若是以前已经插入的字符串 word 的前缀之一为 prefix ,返回true;不然,返回 false 。

示例:java

输入
["Trie", "insert", "search", "search", "startsWith", "insert", "search"]
[[], ["apple"], ["apple"], ["app"], ["app"], ["app"], ["app"]]
输出
[null, null, true, false, true, null, true]

解释
Trie trie = new Trie();
trie.insert("apple");
trie.search("apple");   // 返回 True
trie.search("app");     // 返回 False
trie.startsWith("app"); // 返回 True
trie.insert("app");
trie.search("app");     // 返回 True

二、算法描述

一、把单词拆分红为一个一个单词经过树形结构的方式进行存储,而后在最后一个字母能使得这条链成为一个单词就记录它为一个单词。
二、所以,若isWord=true的话,这条链就是一个单词,反之则不是。

三、代码实现

一、存储树结构的数据结构算法

package com.bean;

public class TrieNode {
    public boolean isWord;//是不是单词
    public TrieNode[] children;//26个小写字母

    public TrieNode() {
        isWord = true;
        children = new TrieNode[26];
    }
}

二、具体实现增删改查的代码数据结构

package com.java;


import com.bean.TrieNode;

public class Day14_Trie {
    //根节点,根节点是不存储任何字母的,从根节点的
    //子节点开始存储
    private TrieNode root;

    public Day14_Trie() {
        root = new TrieNode();
    }

    //插入字符串
    public void insert(String word) {
        TrieNode current = root;
        for (int i = 0; i < word.length(); i++) {
            int index = word.charAt(i) - 'a';
            //判断字符有没有建立,若是没有建立就建立
            if (current.children[index] == null) {
                current.children[index] = new TrieNode();
                //中间的字符不是完整的单词
                current.children[index].isWord = false;
            }
            current = current.children[index];
        }
        //最后一个字符才能构成一个完整的单词
        current.isWord = true;
    }

    public boolean search(String word) {
        TrieNode current = find(word);
        return current != null && current.isWord;
    }

    public boolean startsWith(String prefix) {
        return find(prefix) != null;
    }

    private TrieNode find(String str) {
        TrieNode current = root;
        int length = str.length();
        for (int i = 0; i < length; i++) {
            int index = str.charAt(i) - 'a';
            if ((current = current.children[index]) == null)
                return null;
        }
        return current;
    }
}
相关文章
相关标签/搜索