Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit4c3aff7

Browse files
add a solution for 1268
1 parent4382494 commit4c3aff7

File tree

1 file changed

+75
-0
lines changed

1 file changed

+75
-0
lines changed

‎src/main/java/com/fishercoder/solutions/_1268.java

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -85,4 +85,79 @@ public TrieNode(char c) {
8585
}
8686
}
8787
}
88+
89+
publicstaticclassSolution2 {
90+
publicList<List<String>>suggestedProducts(String[]products,StringsearchWord) {
91+
TrieNoderoot =buildTrie(products);
92+
List<List<String>>result =newArrayList<>();
93+
for (inti =1;i <=searchWord.length();i++) {
94+
StringsearchTerm =searchWord.substring(0,i);
95+
TrieNodetmp =root;
96+
List<String>searchResult =newArrayList<>();
97+
for (intj =0;j <searchTerm.length();j++) {
98+
charc =searchTerm.charAt(j);
99+
if (tmp.children[c -'a'] ==null) {
100+
break;
101+
}else {
102+
tmp =tmp.children[c -'a'];
103+
}
104+
if (j ==searchTerm.length() -1) {
105+
searchResult.addAll(findAllWords(tmp,searchTerm));
106+
}
107+
}
108+
result.add(searchResult.size() >3 ?searchResult.subList(0,3) :searchResult);
109+
}
110+
returnresult;
111+
}
112+
113+
privateList<String>findAllWords(TrieNodetrieNode,Stringprefix) {
114+
List<String>result =newArrayList<>();
115+
if (trieNode.isWord) {
116+
result.add(prefix);
117+
if (result.size() >3) {
118+
returnresult;
119+
}
120+
}
121+
for (TrieNodenode :trieNode.children) {
122+
if (node !=null) {
123+
result.addAll(findAllWords(node,prefix +node.val));
124+
if (result.size() >3) {
125+
returnresult;
126+
}
127+
}
128+
}
129+
returnresult;
130+
}
131+
132+
privateTrieNodebuildTrie(String[]words) {
133+
TrieNoderoot =newTrieNode(' ');
134+
for (Stringword :words) {
135+
TrieNodetmp =root;
136+
for (inti =0;i <word.length();i++) {
137+
charc =word.charAt(i);
138+
if (tmp.children[c -'a'] ==null) {
139+
tmp.children[c -'a'] =newTrieNode(c);
140+
}
141+
tmp =tmp.children[c -'a'];
142+
if (i ==word.length() -1) {
143+
tmp.isWord =true;
144+
}
145+
}
146+
147+
}
148+
returnroot;
149+
}
150+
151+
publicclassTrieNode {
152+
TrieNode[]children;
153+
charval;
154+
booleanisWord;
155+
156+
publicTrieNode(charval) {
157+
this.children =newTrieNode[26];
158+
this.val =val;
159+
this.isWord =false;
160+
}
161+
}
162+
}
88163
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp