`

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.

For example:

addWord("bad")
addWord("dad")
addWord("mad")
search("pad") -> false
search("bad") -> true
search(".ad") -> true
search("b..") -> true

设计一个字典树的数据结构,实现add和search功能,对于search功能,加了一个模糊匹配搜索,字符' . '可以代表任意一个字符,因此当我们匹配到' . '字符时,我们可以用回溯法从当前字符往下找,如果可以找到就返回true,如果不能找到就回溯从其他点开始。代码如下:
class TrieNode {
    TrieNode[] trieNode;
    boolean isLast;
    public TrieNode() {
        trieNode = new TrieNode[26];
        isLast = false;
    }
}

public class WordDictionary {
    private TrieNode root;
    public WordDictionary() {
        root = new TrieNode();
    }
    // Adds a word into the data structure.
    public void addWord(String word) {
        TrieNode cur = root;
        for(char c : word.toCharArray()) {
            if(cur.trieNode[c - 'a'] == null) 
                cur.trieNode[c - 'a'] = new TrieNode();
            cur = cur.trieNode[c - 'a'];
        }
        cur.isLast = true;
    }

    // Returns if the word is in the data structure. A word could
    // contain the dot character '.' to represent any one letter.
    public boolean search(String word) {
        TrieNode cur = root;
        return search(cur, word, 0);
    }
    public boolean search(TrieNode cur, String word, int index) {
        if(cur == null) return false;
        if(index == word.length()) return cur.isLast;
        char c = word.charAt(index);
        if(c == '.') {
            for(TrieNode node : cur.trieNode) {
                 if(search(node, word, index + 1))
                    return true;
            }
        } else {
            cur = cur.trieNode[c - 'a'];
            return search(cur, word, index + 1);
        }
        return false;
    }
}


// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");
分享到:
评论

相关推荐

    LeetCode最全代码

    201 | [Bitwise AND of Numbers Range](https://leetcode.com/problems/bitwise-and-of-numbers-range/) | [C++](./C++/bitwise-and-of-numbers-range.cpp) [Python](./Python/bitwise-and-of-numbers-range.py) | _...

    1、基础算法必练题(含解法)).pdf

    6. **Add and Search Word - Data structure design**:设计一个数据结构,可以在已有的单词列表中添加新词并搜索模式。这需要一个动态更新的前缀树。 7. **Word Search II**:在一个二维字符网格中找出所有具有...

    lrucacheleetcode-leetcode:算法实践

    lru缓存leetcode ...数据结构设计https://leetcode.com/problems/add-and-search-word-data-structure-design/ 硬字搜索IIhttps://leetcode.com/problems/word-search-ii/ EasyFind the Difference ...

    lrucacheleetcode-python-leetcode:Pythonleetcode

    3. "Add and Search Word - Data structure design"(添加和搜索单词 - 数据结构设计):这个问题涉及构建一个字典树,并结合LRU缓存进行搜索优化。 在"python-leetcode-master"这个压缩包中,很可能包含了一个或多...

    Senfore_DragDrop_v4.1

    4) Add the Drag and Drop Component Suite components directory to your library path. 5) Load the demo project group: demo\dragdrop_delphi.bpg for Delphi 5 and 6 demo\dragdrop_bcb4.bpg for C++ ...

    SSD7 选择题。Multiple-Choice

    (b) the name of the table, the names of the table's attributes, the data types of the table's attributes, the formats of the table's attributes, and the maximum number of rows that the table can have...

    Cassandra

    Discover how Cassandra's distributed design lets you add or remove nodes from the cluster as your application requires, Get examples for writing clients in Java, Python, and C#, Extend Cassandra by ...

    EhLib5.0.13 最新的ehlib源码

    Allows create and fill data in design-time and save data in dfm file of the Form. Allows keep record in the manner of trees. Each record can have record elements-branches and itself be an ...

    EhLib 8.0 Build 8.0.023 Pro Edition FullSource for D7-XE8

    Allows create and fill data in design-time and save data in dfm file of the Form. Allows keep record in the manner of trees. Each record can have record elements-branches and itself be an ...

    EhLib 6.3 Build 6.3.176 Russian version. Full source included.

    Allows create and fill data in design-time and save data in dfm file of the Form. Allows keep record in the manner of trees. Each record can have record elements-branches and itself be an ...

    EhLib 9.1.024

    Allows create and fill data in design-time and save data in dfm file of the Form. Allows keep record in the manner of trees. Each record can have record elements-branches and itself be an ...

    ehlib_vcl_src_9_3.26

    Allows create and fill data in design-time and save data in dfm file of the Form. Allows keep record in the manner of trees. Each record can have record elements-branches and itself be an ...

    Beginning T-SQL with Microsoft SQL Server 2005 and 2008

    Transact-SQL, or T-SQL, is Microsoft Corporation’s powerful implementation of the ANSI standard SQL database query language, which was designed to retrieve, manipulate, and add data to relational ...

    Lerner -- Python Workout. 50 Essential Exercises -- 2020.pdf

    - Understanding XML structure and syntax. - Using the `xml.etree.ElementTree` module for creating XML documents. 26. **Prefix Notation Calculator** - **Objective:** Implement a calculator for ...

    A 3D Modeller-Erick Dransch.zip

    The user must be able to add to and modify the design in order to produce the desired result. Additionally, all tools would need a way to save and load designs from disk so that users can ...

    Practical D3.js(Apress,2016)

    What structure and design strategies you can use for compelling data visualization How to use data binding, animations and events, scales, and color pickers How to use shapes, path generators, arcs ...

    FastReport.v4.15 for.Delphi.BCB.Full.Source企业版含ClientServer中文修正版支持D4-XE5

    Current version allows preview, print and design report template under Windows and Linux platform (qt). + Added Embarcadero RAD Studio XE3 support - fixed compatibility with Fast Report FMX installed...

    Lecture_1_Introduction.pdf

    2. **Design Efficient Algorithms:** Students will develop skills to design and analyze algorithms that are efficient in terms of time and space complexity. 3. **Apply Knowledge to Real-World Problems:...

Global site tag (gtag.js) - Google Analytics