LeetCode Add and Search Word - Data structure design

来源:互联网 发布:威尼斯人信誉第一js 编辑:程序博客网 时间:2024/06/16 16:25

Description:

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") -> falsesearch("bad") -> truesearch(".ad") -> truesearch("b..") -> true

Solution:

就实现一个Trie树即可,相比于AC自动机简单很多(没有fail指针)

需要注意的是因为有"."的存在,需要进行一个匹配操作,所以普通的一层循环没法解决,我用了队列,将所有可能的TrieNode都进行维护,然后按照层次遍历




<span style="font-size:18px;">import java.util.LinkedList;public class WordDictionary {TrieNode root = new TrieNode();// Adds a word into the data structure.public void addWord(String word) {int ch;TrieNode tot = root;for (int i = 0; i < word.length(); i++) {ch = word.charAt(i) - 'a';if (tot.children[ch] == null)tot.children[ch] = new TrieNode();tot = tot.children[ch];}tot.isWord = true;}// 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) {LinkedList<TrieNode> queue = new LinkedList<TrieNode>();queue.add(root);int level = 0;TrieNode node;int ch;int n = word.length();while (!queue.isEmpty()) {int size = queue.size();level++;if (level == n + 1) {for (int i = 0; i < size; i++) {node = queue.poll();if (node.isWord)return true;}} else {ch = word.charAt(level - 1) - 'a';for (int i = 0; i < size; i++) {node = queue.poll();if (ch == -51) {for (int j = 0; j < 26; j++)if (node.children[j] != null)queue.add(node.children[j]);} else {if (node.children[ch] != null)queue.add(node.children[ch]);}}}}return false;}class TrieNode {TrieNode[] children = new TrieNode[26];boolean isWord = false;}public static void main(String[] args) {System.out.println('.' - 'a');WordDictionary w = new WordDictionary();w.addWord("a");System.out.println(w.search("."));}}</span>


0 0