Skip to content

Commit 5eef00f

Browse files
committed
Add solution #745
1 parent 07c5c58 commit 5eef00f

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -273,6 +273,7 @@
273273
733|[Flood Fill](./0733-flood-fill.js)|Easy|
274274
735|[Asteroid Collision](./0735-asteroid-collision.js)|Medium|
275275
739|[Daily Temperatures](./0739-daily-temperatures.js)|Medium|
276+
745|[Prefix and Suffix Search](./0745-prefix-and-suffix-search.js)|Hard|
276277
746|[Min Cost Climbing Stairs](./0746-min-cost-climbing-stairs.js)|Easy|
277278
747|[Largest Number At Least Twice of Others](./0747-largest-number-at-least-twice-of-others.js)|Easy|
278279
748|[Shortest Completing Word](./0748-shortest-completing-word.js)|Easy|
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
/**
2+
* 745. Prefix and Suffix Search
3+
* https://leetcode.com/problems/prefix-and-suffix-search/
4+
* Difficulty: Hard
5+
*
6+
* Design a special dictionary that searches the words in it by a prefix and a suffix.
7+
*
8+
* Implement the WordFilter class:
9+
* - WordFilter(string[] words) Initializes the object with the words in the dictionary.
10+
* - f(string pref, string suff) Returns the index of the word in the dictionary, which
11+
* has the prefix pref and the suffix suff. If there is more than one valid index,
12+
* return the largest of them. If there is no such word in the dictionary, return -1.
13+
*/
14+
15+
/**
16+
* @param {string[]} words
17+
*/
18+
var WordFilter = function(words) {
19+
this.map = new Map();
20+
21+
for (let i = 0; i < words.length; i++) {
22+
let prefix = '';
23+
24+
for (let j = 0; j <= words[i].length; j++) {
25+
let suffix = '';
26+
27+
for (let k = 0; k <= words[i].length; k++) {
28+
suffix = words[i].slice(k);
29+
this.map.set(prefix + '#' + suffix, i);
30+
}
31+
32+
prefix += words[i][j];
33+
}
34+
}
35+
};
36+
37+
/**
38+
* @param {string} pref
39+
* @param {string} suff
40+
* @return {number}
41+
*/
42+
WordFilter.prototype.f = function(pref, suff) {
43+
const target = `${pref}#${suff}`;
44+
return this.map.has(target) ? this.map.get(target) : -1;
45+
};

0 commit comments

Comments
 (0)