我的LeetCode代码仓:https://github.com/617076674/LeetCode

原题链接:https://leetcode-cn.com/problems/add-and-search-word-data-structure-design/description/

题目描述:

LeetCode211——添加与搜索单词 - 数据结构设计

知识点:Trie

思路:Trie存储单词

关于Trie的实现,可以参见LeetCode208——实现 Trie (前缀树)

addWord和search的时间复杂度均是O(n),其中n为待添加单词的长度。

JAVA代码:

class WordDictionary {
	private class Node {
		private boolean isWord;
		private HashMap<Character, Node> next;
		public Node() {
			isWord = false;
			next = new HashMap<>();
		}
	}
	private Node root;
    public WordDictionary() {
    	root = new Node();
    }
    public void addWord(String word) {
    	Node cur = root;
    	for (int i = 0; i < word.length(); i++) {
			char c = word.charAt(i);
			if(cur.next.get(c) == null) {
				cur.next.put(c, new Node());
			}
			cur = cur.next.get(c);
		}
    	if(!cur.isWord) {
    		cur.isWord = true;
    	}
    }
    public boolean search(String word) {
    	return match(root, word, 0);
    }
	private boolean match(Node node, String word, int i) {
		if(i == word.length()) {
			return node.isWord;		//不应该直接返回true,这是不是一个单词要看这个节点的isWord属性
		}
		char c = word.charAt(i);
		if(c != '.') {
			if(node.next.get(c) == null) {
				return false;
			}
			return match(node.next.get(c), word, i + 1);
		}else {
			for(char nextChar : node.next.keySet()) {
				if(match(node.next.get(nextChar), word, i + 1)) {
					return true;
				}
			}
			return false;
		}
	}
}

LeetCode解题报告:

LeetCode211——添加与搜索单词 - 数据结构设计

 

相关文章:

  • 2022-01-24
  • 2021-11-18
  • 2021-07-25
  • 2021-09-17
  • 2021-07-13
  • 2021-04-14
  • 2021-11-30
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-11
  • 2022-12-23
  • 2022-12-23
  • 2021-05-31
  • 2021-10-03
相关资源
相似解决方案