[LeetCode] 745. Prefix and Suffix Search
Problem
Given many words, words[i] has weight i.
Design a class WordFilter that supports one function, WordFilter.f(String prefix, String suffix). It will return the word with given prefix and suffix with maximum weight. If no word exists, return -1.
Examples:
Input:
WordFilter(["apple"])
WordFilter.f("a", "e") // returns 0
WordFilter.f("b", "") // returns -1
Note:
words has length in range [1, 15000].
For each test case, up to words.length queries WordFilter.f may be made.
words[i] has length in range [1, 10].
prefix, suffix have lengths in range [0, 10].
words[i] and prefix, suffix queries consist of lowercase letters only.
Soluton (HashMap)
class WordFilter {
Map<String, Integer> map = new HashMap<>();
public WordFilter(String[] words) {
for (int i = 0; i < words.length; i++) {
map.put(words[i], i);
}
}
//find max-length string index
public int f(String prefix, String suffix) {
if (prefix == null || suffix == null) return -1;
int maxLen = Math.max(prefix.length(), suffix.length());
String resStr = "";
int resIndex = -1;
for (Map.Entry<String, Integer> entry: map.entrySet()) {
String cur = entry.getKey();
int curLen = cur.length();
if (curLen < maxLen) continue;
if (cur.startsWith(prefix) && cur.substring(curLen-suffix.length()).equals(suffix)) {
if (entry.getValue() > resIndex) {
resStr = entry.getKey();
resIndex = entry.getValue();
}
}
}
return resIndex;
}
}
Solution (Trie)
Road to Glory
對酒當歌,人生幾何? 譬如朝露,去日苦多。
161 声望
53 粉丝
推荐阅读
[LeetCode] 958. Check Completeness of a Binary Tree
Definition of a complete binary tree from Wikipedia:In a complete binary tree every level, except possibly the last, is completely filled, and all nodes in the last level are as far left as possibl...
linspiration阅读 1.9k
rust使用hashmap存储函数并调用
背景在rust 1.67.1 (d5a82bbd2 2023-02-07) 版本测试正常使用rust的hashmap存储i32为key, 函数作为value, 当查询某个key如果存在具体的函数则调用支持异步函数存储与调用主要方法如果类型不同,则需要包一层Box,...
龚正阳阅读 259
HashMap源码解析
内部是以数组的形式存储了Entry对象,而每个Entry对象里面有key和value用来存值.它里面包含了key、value、next、hash四个字段,其中next字段是用来引用下一个Entry的(相同的hash值会被放入同一个链表中).数组中的每...
潇风寒月阅读 127
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。