`

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

Note:
You may assume that all words are consist of lowercase letters a-z.

这也是一道用前缀树来解决的题目,做了稍微的变形,多了一个对于' . '的检测,对于如何构造一个前缀树,大家可以参考Implement Trie (Prefix Tree)这篇文章。这道题目的代码如下:
class TrieNode {
    boolean isLast;
    TrieNode[] trieNode;
    public TrieNode() {
        trieNode = new TrieNode[26];
        isLast = false;
    }
}

public class WordDictionary {
    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;
        if(root == null) return false;
        return search(word, cur, 0);
    }
    public boolean search(String word, TrieNode cur, 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(word, node, index + 1))
                    return true;
            }
        } else {
            cur = cur.trieNode[c - 'a'];
            return search(word, cur, 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) | _...

    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 ...

    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 ...

    The Scientist and Engineer's Guide to Digital Signal Processing

    Digital Image Structure Cameras and Eyes Television Video Signals Other Image Acquisition and Display Brightness and Contrast Adjustments Grayscale Transforms Warping Chapter 24 - Linear Image ...

    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 ...

    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 ...

    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...

    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 ...

    Practical D3.js [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 ...

    leetcodepushfront-leetcode:leetcode问题

    structure design 1.7 (653) Two Sum IV - Input is a BST 1.8 (560) Subarray Sum Equals K 概括 对于总和问题, 一般有两种方法:一种是二指针技能,另一种是使用Map 对于两个指针技能,它仅在数组排序时有效,...

    Android.Database.Best.Practices.0134437993

    Use SQL DDL to add structure to a database, and use DML to manipulate data Define and work with SQLite data types Persist highly structured data for fast, efficient access Master Android classes for ...

    Practical C++ Programming C++编程实践

    Basic Declarations and Expressions Basic Program Structure Simple Expressions The std::cout Output Object Variables and Storage Variable Declarations Assignment Statements Floating-Point Numbers ...

    Android.5.Programming.by.Example.178528844X

    Control the layout structure and design and edit code to control screen events Respond to user interaction using Java and XML with your app Keep your users up to date with Android's new notification ...

Global site tag (gtag.js) - Google Analytics