码迷,mamicode.com
首页 > 其他好文 > 详细

(*medium)LeetCode 211.Add and Search Word - Data structure design

时间:2015-08-16 16:25:30      阅读:101      评论:0      收藏:0      [点我收藏+]

标签:

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.

click to show hint.

You should be familiar with how a Trie works. If not, please work on this problem: Implement Trie (Prefix Tree) first.
方法:1:暴力解法,超时
代码如下:
public class WordDictionary {

    private List<String>list=new ArrayList<>();
    // Adds a word into the data structure.
    public void addWord(String word) {
        list.add(word);
    }

    // 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) {
        if(list.contains(word)){
            return true;
        }else{
            int size=list.size();
            int i=0,j=0;
            for(;i<size;i++){
               String s= list.get(i);
               int len=s.length();
               if(len!=word.length())
                   continue;
                   j=0;
               for(;j<len;j++){
                   if(word.charAt(j)==‘.‘)
                       continue;
                   else{
                       if(s.charAt(j)!=word.charAt(j)){
                           break;
                       }
                   }       
               }
              if(j==len) return true;
            }
            return false;
        }
    }
}

// Your WordDictionary object will be instantiated and called as such:
// WordDictionary wordDictionary = new WordDictionary();
// wordDictionary.addWord("word");
// wordDictionary.search("pattern");

运行结果:

技术分享

方法2:按照提示,使用单词查字树

代码如下:

 

 

(*medium)LeetCode 211.Add and Search Word - Data structure design

标签:

原文地址:http://www.cnblogs.com/mlz-2019/p/4734392.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!