zoukankan      html  css  js  c++  java
  • leetcode 211. Add and Search Word

    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.

    基于字典树来设计,还可以优化,把string转换成char[]即可。

    public class WordDictionary {
        
        public WordDictionary[] words;
        public boolean isWord;
        
        /** Initialize your data structure here. */
        public WordDictionary() {
            words = new WordDictionary[26];
        }
        
        /** Adds a word into the data structure. */
        public void addWord(String word) {
            WordDictionary[] wordCh = words;
            for (int i = 0; i < word.length(); i++){
                int pos = (int) (word.charAt(i) - 'a');
                if (wordCh[pos] == null){
                    wordCh[pos] = new WordDictionary();
                }
                if (i == word.length() - 1){
                    wordCh[pos].isWord = true;
                }
                wordCh = wordCh[pos].words;
            }
        }
        
        /** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. 
            注意search与startsWith的区别
        */
        public boolean search(String word) {
            
            if (word.length() == 0){
                return isWord;
            }
            if (word.charAt(0) == '.'){
                for (int i = 0; i < 26; i++){
                    if (words[i] != null && words[i].search(word.substring(1, word.length()))){
                        return true;
                    }
                }
                return false;
            }
            if (words[word.charAt(0) - 'a'] == null){
                return false;
            } else {
                return words[word.charAt(0) - 'a'].search(word.substring(1, word.length()));
            }
        }
    }
    
    /**
     * Your WordDictionary object will be instantiated and called as such:
     * WordDictionary obj = new WordDictionary();
     * obj.addWord(word);
     * boolean param_2 = obj.search(word);
     */
  • 相关阅读:
    Windows修改MySQL用户root密码
    ORA-24247: 网络访问被访问控制列表 (ACL) 拒绝
    DM8 HUGE表使用小技巧
    DEM 安装部署
    【.NET 框架】—— Dapper框架的高级应用(二)
    JWT理论理解
    SqlServer使用表变量或临时表遍历数据
    NPOI Excel Helper
    Celery异步分布队列
    Django-Admin和第三方插件Xadmin
  • 原文地址:https://www.cnblogs.com/xiaoba1203/p/6635382.html
Copyright © 2011-2022 走看看