当前位置:网站首页>面试题 17.11. 单词距离 ●●
面试题 17.11. 单词距离 ●●
2022-07-25 22:33:00 【keep_fan】
面试题 17.11. 单词距离 ●●
描述
有个内含单词的超大文本文件,给定任意两个不同的单词,找出在这个文件中这两个单词的最短距离(相隔单词数)。
进阶问题:
如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,你能对此优化吗?
示例
输入:words = [“I”,“am”,“a”,“student”,“from”,“a”,“university”,“in”,“a”,“city”], word1 = “a”, word2 = “student”
输出:1
题解
1. 双指针
建立两个指针,在遍历字符串数组的过程中,两个指针分别指向已遍历范围内,对应单词的最大下标 idx1 和 idx2 (即遇到对应单词变更新指针位置),每次计算并更新间隔距离。
- 时间复杂度:O(n),其中 nn 是数组 words 的长度。需要遍历数组一次计算 word1 和 word2 的最短距离,每次更新下标和更新最短距离的时间都是 O(1)。这里将字符串的长度视为常数。
- 空间复杂度:O(1)。

class Solution {
public:
int findClosest(vector<string>& words, string word1, string word2) {
int idx1 = -1, idx2 = -1;
int ans = INT_MAX;
for(int i = 0; i < words.size(); ++i){
if(words[i] == word1 || words[i] == word2){
if(words[i] == word1){
// 更新指针
idx1 = i;
}else{
idx2 = i;
}
if(idx1 >= 0 && idx2 >= 0){
// 更新距离
ans = min(ans, abs(idx1 - idx2));
if(ans == 1) return 1;
}
}
}
return ans;
}
};
进阶问题:
如果寻找过程在这个文件中会重复多次,而每次寻找的单词不同,
则可以维护一个哈希表记录每个单词的下标列表。
遍历一次文件,按照下标递增顺序得到每个单词在文件中出现的所有下标。
在寻找单词时,只要得到两个单词的下标列表,使用双指针遍历两个下标链表,即可得到两个单词的最短距离。
边栏推荐
- Wechat official account application development (I)
- xss-收集常用的代码
- [training Day12] x equation [high precision] [mathematics]
- 力扣解法汇总919-完全二叉树插入器
- Xiaobai programmer's first day
- Select structure if branch structure
- IPv4 addresses have been completely exhausted, and the Internet can work normally. NAT is the greatest contributor!
- Examples and points for attention about the use of getchar and scanf
- Today, let's talk about the if branch statement of the selection structure
- Wechat applet (anti shake, throttling), which solves the problem that users keep pulling down refresh requests or clicking buttons to submit information; Get the list information and refresh the data
猜你喜欢
随机推荐
对需求的内容进行jieba分词并按词频排序输出excel文档
xss-工具-Beef-Xss安装以及使用
Share two music playing addresses
Today, let's talk about the if branch statement of the selection structure
【集训DAY13】Travel【暴力】【动态规划】
scrapy无缝对接布隆过滤器
Div drag effect
Data governance under data platform
【Leetcode】502.IPO(困难)
Build commercial projects based on ruoyi framework
Naming rules of software test pytest pytest the pre and post confitest of use cases Py customized allure report @pytest.mark.parameter() decorator as data-driven
【集训DAY15】油漆道路【最小生成树】
Compiler introduction
【集训DAY13】Backpack【动态规划】【贪心】
Wkid in ArcGIS
访问者模式(visitor)模式
面向领域模型编程
3dslicer introduction and installation tutorial
我们为什么要推出Getaverse?
(1) Integrating two mapping frameworks of Dao






![[training day15] good name [hash]](/img/62/5cd354e63aab861bf8fa1f265b6986.png)


