zoukankan      html  css  js  c++  java
  • Java实现 LeetCode 211 添加与搜索单词

    211. 添加与搜索单词 - 数据结构设计

    设计一个支持以下两种操作的数据结构:

    void addWord(word)
    bool search(word)
    

    search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。

    示例:

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

    说明:

    你可以假设所有单词都是由小写字母 a-z 组成的。

    class WordDictionary {
    
        Map<Integer,Set<String>> map = new HashMap<>();//根据字符串长度分开存放
        public WordDictionary() {
            
        }
        public void addWord(String word) {
            int length = word.length();
            if(map.get(length)!=null){
                map.get(length).add(word);
            }else{
                Set<String> set = new HashSet<>();
                set.add(word);
                map.put(length, set);
            }
        }
        public boolean search(String word) {
            Set<String> set = map.get(word.length());
            if(set==null){  //不存在该长度的字符串,直接返回false;
                return false;
            }
            if(set.contains(word)) return true;
            char[] chars = word.toCharArray();
            P:for(String s : set){
                if(word.length()!=s.length()){
                    continue;
                }
                char[] cs = s.toCharArray();
                for(int i = 0; i< cs.length; i++){//逐个字符对比
                    if(chars[i] != '.' && chars[i] != cs[i]){
                        continue P;
                    }
                }
                set.add(word);
                return true;
            }
            return false;
        }
    }
    
    /**
     * Your WordDictionary object will be instantiated and called as such:
     * WordDictionary obj = new WordDictionary();
     * obj.addWord(word);
     * boolean param_2 = obj.search(word);
     */
    
  • 相关阅读:
    C# 文件类的操作---删除
    C#实现Zip压缩解压实例
    UVALIVE 2431 Binary Stirling Numbers
    UVA 10570 meeting with aliens
    UVA 306 Cipher
    UVA 10994 Simple Addition
    UVA 696 How Many Knights
    UVA 10205 Stack 'em Up
    UVA 11125 Arrange Some Marbles
    UVA 10912 Simple Minded Hashing
  • 原文地址:https://www.cnblogs.com/a1439775520/p/13075387.html
Copyright © 2011-2022 走看看