leetcode--Shortest Word Distance II

本文介绍了一种高效算法,用于解决给定单词列表中两指定单词间的最短距离问题。通过预处理单词位置并利用双指针技巧实现快速查询。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it? 

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. 

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

Given word1 = “coding”, word2 = “practice”, return 3. 
Given word1 = "makes", word2 = "coding", return 1. 

Note: 

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

题意:给定数组,和两个word,word,要求构造一个类,计算两者的最短距离,因为我们要给出很多组不同的两个word,你会怎么组织这个类呢?

分类:数组


解法1:在构造函数,使用hashMap来记录每个单词的位置

在计算最短距离的函数中,两个列表是已排序的,因此可使用类似MergeSort的思路求解最短距离。 

[java]  view plain  copy
  1. public class WordDistance {  
  2.     private HashMap<String, List<Integer>> indexer = new HashMap<String, List<Integer>>();  
  3.     public WordDistance(String[] words) {  
  4.         if (words == nullreturn;  
  5.         for (int i = 0; i < words.length; i++) {  
  6.             if (indexer.containsKey(words[i])) {  
  7.                 indexer.get(words[i]).add(i);  
  8.             } else {  
  9.                 List<Integer> positions = new ArrayList<Integer>();  
  10.                 positions.add(i);  
  11.                 indexer.put(words[i], positions);  
  12.             }  
  13.         }  
  14.     }  
  15.   
  16.     public int shortest(String word1, String word2) {  
  17.         List<Integer> posList1 = indexer.get(word1);  
  18.         List<Integer> posList2 = indexer.get(word2);  
  19.         int i = 0, j = 0;  
  20.         int diff = Integer.MAX_VALUE;  
  21.         while (i < posList1.size() && j < posList2.size()) {  
  22.             int pos1 = posList1.get(i), pos2 = posList2.get(j);  
  23.             if (pos1 < pos2) {  
  24.                 diff = Math.min(diff, pos2 - pos1);  
  25.                 i++;  
  26.             } else {  
  27.                 diff = Math.min(diff, pos1 - pos2);  
  28.                 j++;  
  29.             }  
  30.         }  
  31.         return diff;  
  32.     }  
  33. }  

原文链接http://blog.youkuaiyun.com/crazy__chen/article/details/47859865

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值