Saturday, May 7, 2022

Leet Code 211. Design Add and Search Words Data Structure

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

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...