Design a data structure that supports adding new words and finding if a string matches any previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) Adds word to the data structure, it can be matched later.
bool search(word) Returns true if there is any string in the data structure that matches word or false otherwise. word may contain dots ‘.’ where dots can be matched with any letter.
// O(N^2 * M) classWordDictionary{ Map<Integer, Set<String>> d;
/** Initialize your data structure here. */ publicWordDictionary(){ d = new HashMap(); }
/** Adds a word into the data structure. */ publicvoidaddWord(String word){ int m = word.length(); if (!d.containsKey(m)) { d.put(m, new HashSet()); } d.get(m).add(word); }
/** Returns if the word is in the data structure. A word could contain the dot character '.' to represent any one letter. */ publicbooleansearch(String word){ int m = word.length(); if (d.containsKey(m)) { for (String w : d.get(m)) { int i = 0; while ((i < m) && (w.charAt(i) == word.charAt(i) || word.charAt(i) == '.')) { i++; } if (i == m) returntrue; } } returnfalse; } }
Solution 2: Trie Tree, O(MN) for defined words without dots, O(NM^26) for undefined words
v1.5.2