zoukankan      html  css  js  c++  java
  • Leecode no.211 添加与搜索单词

    package leecode;

    /**
    * @Author:tang
    * @CreateDate 2021/5/12
    *
    * 请你设计一个数据结构,支持 添加新单词 和 查找字符串是否与任何先前添加的字符串匹配 。
    *
    * WordDictionary() 初始化词典对象
    * void addWord(word) 将 word 添加到数据结构中,之后可以对它进行匹配
    * bool search(word) 如果数据结构中存在字符串与 word 匹配,则返回 true ;否则,返回 false 。word 中可能包含一些 '.' ,每个 . 都可以表示任何一个字母。
    */
    public class WordDictionary {

    char[] dict;

    StringBuilder words;

    WordDictionary(){
    words = new StringBuilder();
    }

    void addWord(String word){
    words.append(word);
    }

    boolean search(String word){
    dict = words.toString().toCharArray();
    for(int i = 0; i < dict.length-word.length()+1; i++){
    if(matching(i, 0, word.toCharArray())){
    return true;
    }
    }
    return false;
    }

    /**
    * 比较开始字典 与word能否完全匹配
    * @param indexDict
    * @param indexWord
    * @param words
    * @return
    */
    private boolean matching(int indexDict, int indexWord, char[] words){
    if(indexWord > words.length -1){
    return true;
    }
    if(indexDict > dict.length -1){
    return false;
    }
    if(dict[indexDict] == words[indexWord] || words[indexWord] == '.'){
    return matching(indexDict +1, indexWord +1, words);
    }
    return false;
    }

    public static void main(String[] args) {

    WordDictionary wordDictionary = new WordDictionary();
    wordDictionary.addWord("a");
    wordDictionary.addWord("a");
    //wordDictionary.addWord("found");
    System.out.println(wordDictionary.search("a"));
    System.out.println(wordDictionary.search("aa"));
    System.out.println(wordDictionary.search("."));
    System.out.println(wordDictionary.search("a."));
    System.out.println(wordDictionary.search(".a"));
    }

    }
  • 相关阅读:
    css div中加入滚动条
    oracle创建表主键触发器
    SQL Server 日志满的处理方法(转)
    Asp.net 设置页面自动刷新
    设置DataGrid可读取中隐藏列数据
    用JavaScript获取Asp.net服务器端控件CheckBoxList的选中值数组(转)
    AutoLISP查询椭圆的相关属性
    AutoLISP查询圆弧的相关属性
    关于性格内向者的10个误解
    AutoLISP查询图元信息
  • 原文地址:https://www.cnblogs.com/ttaall/p/14781796.html
Copyright © 2011-2022 走看看