Add and Search Word (单词的添加与查找)

http://www.lintcode.com/zh-cn/problem/add-and-search-word/

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class WordDictionary {
    private HashMap> map = new HashMap<>();

    /*
     * @param word: Adds a word into the data structure.
     * @return: nothing
     */
    public void addWord(String word) {
        // write your code here
        char c = word.charAt(0);
        if (map.containsKey(c)) {
            map.get(c).add(word);
        } else {
            List list = new ArrayList<>();
            list.add(word);
            map.put(c, list);
        }
    }

    /*
     * @param word: A word could contain the dot character '.' to represent any one letter.
     * @return: if the word is in the data structure.
     */
    public boolean search(String word) {
        // write your code here
        char c = word.charAt(0);
        if (c == '.') {
            for (Character key :
                    map.keySet()) {
                if (compare(word, key)) {
                    return true;
                }
            }
        } else {
            if (compare(word, c)) {
                return true;
            }
        }
        return false;
    }

    private boolean compare(String word, Character key) {
        if (!map.containsKey(key)) {
            return false;
        }
        for (String temp : map.get(key)) {
            if (temp.length() == word.length()) {
                int i = 1;
                while (i < word.length()) {
                    if (temp.charAt(i) == word.charAt(i) || word.charAt(i) == '.') {
                        i++;
                    } else {
                        break;
                    }
                }
                if (i == word.length()) {
                    return true;
                }
            }
        }
        return false;
    }
}


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

你可能感兴趣的:(Add and Search Word (单词的添加与查找))