-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathCompleteString.java
More file actions
99 lines (78 loc) · 2.56 KB
/
CompleteString.java
File metadata and controls
99 lines (78 loc) · 2.56 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* Question link: https://www.codingninjas.com/codestudio/problems/complete-string_2687860
*/
public class CompleteString {
public static void main(String[] args) {
String[] words = {"n", "ni", "nin", "ninj", "ninja", "ninga"};
Solution solution = new Solution();
String ans = solution.completeString(6, words);
System.out.println(ans);
}
static class Solution {
private static class TrieNode{
private TrieNode[] children;
int count;
boolean isEndOfWord;
TrieNode() {
children = new TrieNode[26];
count = 0;
isEndOfWord = false;
}
boolean containsChild(char c) {
return children[c - 97] == null;
}
TrieNode getChild(char c) {
return children[c - 97];
}
void addChild(char c) {
children[c - 97] = new TrieNode();
}
void setIsEndOfWord() {
isEndOfWord = true;
}
boolean getIsEndOfWord() {
return isEndOfWord;
}
}
public static String completeString(int n, String[] a) {
// Write your code here.
TrieNode root = new TrieNode();
for (String s: a)
createTrie(root, s, 0);
String ans = "";
for(String s: a)
{
if (isCompleteString(root, s, 0))
{
if(s.length() > ans.length() || (ans.length() == s.length() && s.compareTo(ans) < 0))
ans = s;
}
}
//String empty;
if (ans == "") return "None";
return ans;
}
private static void createTrie(TrieNode root, String s, int x) {
if (x == s.length()) {
root.setIsEndOfWord();
return;
}
char child = s.charAt(x);
if (root.containsChild(child)) {
root.addChild(child);
}
createTrie(root.getChild(child), s, x + 1);
}
private static boolean isCompleteString(TrieNode root, String s, int x) {
if (x == s.length())
{
return true;
}
char c = s.charAt(x);
TrieNode child = root.getChild(c);
if(!child.getIsEndOfWord())
return false;
return isCompleteString(child, s, x + 1);
}
}
}