题目地址:https://leetcode-cn.com/problems/shortest-word-distance-ii/

题目描述

Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the list. Your method will be called repeatedly many times with different parameters.

Example:

Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

题目大意

请设计一个类,使该类的构造函数能够接收一个单词列表。然后再实现一个方法,该方法能够分别接收两个单词 word1 和 word2,并返回列表中这两个单词之间的最短距离。您的方法将被以不同的参数调用 多次。

解题方法

字典保存出现位置

这个题让我们求两个字符串出现的最短距离,其实很好办,先分别找到这两个单词出现的位置,然后两两比较,找出最短距离即可。因为给出的words里面会有重复,所以应该使用unordered_map<string, vector<int>> positions;保存所有出现的位置。

C++代码如下:

class WordDistance {
public:
WordDistance(vector<string>& words) {
for (int i = 0; i < words.size(); ++i) {
positions[words[i]].push_back(i);
}
} int shortest(string word1, string word2) {
vector<int> pos1 = positions[word1];
vector<int> pos2 = positions[word2];
int res = INT_MAX;
for (int p1 : pos1) {
for (int p2 : pos2) {
res = min(res, abs(p1 - p2));
}
}
return res;
}
private:
unordered_map<string, vector<int>> positions;
}; /**
* Your WordDistance object will be instantiated and called as such:
* WordDistance* obj = new WordDistance(words);
* int param_1 = obj->shortest(word1,word2);
*/

日期

2019 年 9 月 22 日 —— 熬夜废掉半条命

最新文章

  1. ElasticSearch第四步-查询详解
  2. C# BS消息推送 SignalR Hubs环境搭建与开发(二)
  3. Android笔记——判断程序是否第一次启动
  4. nginx 配置虚拟主机
  5. Java for LeetCode 149 Max Points on a Line
  6. centos7下安装vsftpd配置
  7. tomcat部署到根路径
  8. Java多线程——&lt;一&gt;概述、定义任务
  9. hdu 2177 取(2堆)石子游戏 博弈论
  10. Linux07--Shell程序设计03 通配符与正则表达式
  11. js导出execl兼容ie Chrome Firefox各种主流浏览器(js export execl)
  12. CSS单行、多行文本溢出显示省略号(……)
  13. JSDOM优化
  14. hdu1540 区间操作,合并,模板题
  15. java网络编程(3)——UDP
  16. java的泛型
  17. index_levedb.go
  18. win10 安装docker
  19. web项目 easyui-datagrid开发实践
  20. SparkStreaming+Kafa+HBase

热门文章

  1. mysql-select as
  2. Deep Learning(深度学习)整理,RNN,CNN,BP
  3. 日常Java 2021/10/21
  4. 『学了就忘』Linux启动引导与修复 — 68、Linux系统运行级别
  5. Spark基础:(三)Spark 键值对操作
  6. Flink(三)【核心编程】
  7. 大数据学习day11------hbase_day01----1. zk的监控机制,2动态感知服务上下线案例 3.HDFS-HA的高可用基本的工作原理 4. HDFS-HA的配置详解 5. HBASE(简介,安装,shell客户端,java客户端)
  8. angular中路由跳转并传值四种方式
  9. 4.2 rust 命令行参数
  10. Linux基础命令---sendmail发送邮件