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;
        }
    }
    
  • 相关阅读:
    08-JS中table隔行换色
    07-JS中 li 排序
    HTML DOM 事件
    JavaScript 事件
    jQuery事件函数
    JQuery与JS对象相互转换
    jQuery中的选择器
    jQuery实现放大镜特效
    java线程(2016-4-7)
    Java 线程的转换及状态
  • 原文地址:https://www.cnblogs.com/reboot329/p/5877845.html
Copyright © 2011-2022 走看看