LeetCode每日一题(745. Prefix and Suffix Search)

Design a special dictionary with some words that searchs the words in it by a prefix and a suffix.

Implement the WordFilter class:

WordFilter(string[] words) Initializes the object with the words in the dictionary.
f(string prefix, string suffix) Returns the index of the word in the dictionary, which has the prefix prefix and the suffix suffix. If there is more than one valid index, return the largest of them. If there is no such word in the dictionary, return -1.

Example 1:

Input
[“WordFilter”, “f”] > [[[“apple”]], [“a”, “e”]]
Output
[null, 0]

Explanation
WordFilter wordFilter = new WordFilter([“apple”]);
wordFilter.f(“a”, “e”); // return 0, because the word at index 0 has prefix = “a” and suffix = 'e".

Constraints:

  • 1 <= words.length <= 15000
  • 1 <= words[i].length <= 10
  • 1 <= prefix.length, suffix.length <= 10
  • words[i], prefix and suffix consist of lower-case English letters only.
  • At most 15000 calls will be made to the function f.

把每个单词按字母处理成 suffix#prefix 组合形式, 然后就可以进行查询了, 查询时时间复杂度为 O(1), 这里要注意的是,每个 suffix#prefix 的 key 仅需要对应一个最大的 index 就好了, 因为查询就是这么要求的


use std::collections::HashMap;

struct WordFilter {
    m: HashMap<String, i32>,
}

/**
 * `&self` means the method takes an immutable reference.
 * If you need a mutable reference, change it to `&mut self` instead.
 */
impl WordFilter {
    fn new(words: Vec<String>) -> Self {
        let mut m = HashMap::new();
        for (i, word) in words.into_iter().enumerate() {
            let mut prefix = String::new();
            for pc in word.chars() {
                prefix.push(pc);
                let mut suffix = String::new();
                for sc in word.chars().rev() {
                    suffix.insert(0, sc);
                    *m.entry(suffix.clone() + "#" + &prefix).or_insert(0) = i as i32;
                }
            }
        }
        Self { m }
    }

    fn f(&self, prefix: String, suffix: String) -> i32 {
        *self.m.get(&(suffix + "#" + &prefix)).unwrap_or(&-1)
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值