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


    June-20-2019

    多了个wildcard,无非是wildcard的时候下一层所有的NODE遍历一下。这个时候需要传下去substring和下层的node,所以多建了个search(string, node)
    秒之

    class WordDictionary {
        
        public class Node {
            Character letter;
            boolean isLetter;
            Map<Character, Node> nextLevel;
            
            public Node(Character letter) {
                nextLevel = new HashMap<>();
                this.letter = letter;
                this.isLetter = false;
            }
        }
        
        Node root;
    
        /** Initialize your data structure here. */
        public WordDictionary() {
            root = new Node(null);
        }
        
        /** Adds a word into the data structure. */
        public void addWord(String word) {
            Node temp = root;
            for (int i = 0; i < word.length(); i ++) {
                char tempChar = word.charAt(i);
                if (!temp.nextLevel.containsKey(tempChar)) {
                    temp.nextLevel.put(tempChar, new Node(tempChar));
                }
                temp = temp.nextLevel.get(tempChar);
            }
            temp.isLetter = 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) {
            
            return search(word, root);
        }
        
        public boolean search(String s, Node temp) {
            for (int i = 0; i < s.length(); i ++) {
                Character c = s.charAt(i);
                if (temp.nextLevel.containsKey(c)) {
                    return search(s.substring(i + 1), temp.nextLevel.get(c));
                } else {
                    if (c == '.') {
                        for (Map.Entry<Character, Node> entry : temp.nextLevel.entrySet()) {
                            if (search(s.substring(i + 1), entry.getValue())) return true;
                        }
                        return false;
                    } else {
                        return false;
                    }
                }
            }
            return temp.isLetter;
        }
    }
    
  • 相关阅读:
    关于Android的布局
    一个新的开端
    Flux的基础概念和实战入门
    在Redux中使用插件createAction之后
    学习
    Object.assign() 对象的扩展
    Redux 中的CombineReducer的函数详解
    React组件的防呆机制(propTypes)
    css的新特性 calc () 使用
    shim和polyfill有什么区别
  • 原文地址:https://www.cnblogs.com/reboot329/p/5877845.html
Copyright © 2011-2022 走看看