https://leetcode.com/problems/design-add-and-search-words-data-structure/
Example:
Input ["WordDictionary","addWord","addWord","addWord","search","search","search","search"] [[],["bad"],["dad"],["mad"],["pad"],["bad"],[".ad"],["b.."]] Output [null,null,null,null,false,true,true,true] Explanation WordDictionary wordDictionary = new WordDictionary(); wordDictionary.addWord("bad"); wordDictionary.addWord("dad"); wordDictionary.addWord("mad"); wordDictionary.search("pad"); // return False wordDictionary.search("bad"); // return True wordDictionary.search(".ad"); // return True wordDictionary.search("b.."); // return True
package pep.Day79;
public class LeetCode_211_Design_Add_and_Search_Words_DataStructure {
static class WordDictionary {
static class Node {
Node children[];
boolean isEnding;
Node() {
children = new Node[26];
}
public boolean find(String word) {
if (word.length() == 0)
return isEnding;
char ch = word.charAt(0);
if (ch == '.') {
int i = 0;
for (Node child : this.children) {
System.out.println(i++);
if (child != null && child.find(word.substring(1)) == true)
return true;
}
} else {
// children me woh character nhi hai
if (children[ch - 'a'] == null)
return false;
else {
// children me woh character mil gya
return children[ch - 'a'].find(word.substring(1));
}
}
return false;
}
}
static Node root;
public WordDictionary() {
root = new Node();
}
public static void addWord(String word) {
Node current = root;
for (int i = 0; i < word.length(); i++) {
if (current.children[word.charAt(i) - 'a'] == null)
current.children[word.charAt(i) - 'a'] = new Node();
current = current.children[word.charAt(i) - 'a'];
}
current.isEnding = true;
}
public boolean search(String word) {
return root.find(word);
}
}
public static void main(String[] args) {
WordDictionary wd = new WordDictionary();
wd.addWord("car");
wd.addWord("cat");
System.out.println(wd.search("c.m"));
}
}

No comments:
Post a Comment