-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Abhishek Surve
committed
Aug 23, 2020
1 parent
0981c94
commit 2213b40
Showing
2 changed files
with
55 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
public class StreamofCharacters { | ||
|
||
class StreamChecker { | ||
|
||
private class TrieNode { | ||
private TrieNode[] next = new TrieNode[26]; | ||
private boolean isWord; | ||
} | ||
|
||
private TrieNode root; | ||
private StringBuilder sb; | ||
|
||
public StreamChecker(String[] words) { | ||
|
||
this.root = new TrieNode(); | ||
this.sb = new StringBuilder(); | ||
|
||
for (String str : words) { | ||
int len = str.length(); | ||
TrieNode node = root; | ||
|
||
for (int i = len - 1; i >= 0; i--) { | ||
char c = str.charAt(i); | ||
if (node.next[c - 'a'] == null) node.next[c - 'a'] = new TrieNode(); | ||
node = node.next[c - 'a']; | ||
} | ||
|
||
node.isWord = true; | ||
} | ||
} | ||
|
||
public boolean query(char letter) { | ||
|
||
sb.append(letter); | ||
TrieNode node = root; | ||
|
||
for (int i = sb.length() - 1; i >= 0 && node != null; i--) { | ||
node = node.next[sb.charAt(i) - 'a']; | ||
if (node != null && node.isWord) { | ||
return true; | ||
} | ||
} | ||
|
||
return false; | ||
} | ||
} | ||
|
||
/** | ||
* Your StreamChecker object will be instantiated and called as such: | ||
* StreamChecker obj = new StreamChecker(words); | ||
* boolean param_1 = obj.query(letter); | ||
*/ | ||
} |