LeetCode 244. 最短单词距离 II

本文介绍了如何设计一个WordDistance类,该类用于计算字符串数组中两个单词之间的最短距离。类的构造函数接受字符串数组,而shortest方法返回给定单词间的最短距离。通过示例展示了类的使用和具体实现。

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

LeetCode 244. 最短单词距离 II

题目描述

请设计一个类,使该类的构造函数能够接收一个字符串数组。然后再实现一个方法,该方法能够分别接收两个单词,并返回列表中这两个单词之间的最短距离。实现 WordDistanc 类:
WordDistance(String[] wordsDict) 用字符串数组 wordsDict 初始化对象。
int shortest(String word1, String word2) 返回数组 worddict 中 word1 和 word2 之间的最短距离。
  示例 1:
  输入:
  [“WordDistance”, “shortest”, “shortest”]
  [[[“practice”, “makes”, “perfect”, “coding”, “makes”]], [“coding”, “practice”], [“makes”, “coding”]]
  输出:
  [null, 3, 1]
  解释:
  WordDistance wordDistance = new WordDistance([“practice”, “makes”, “perfect”, “coding”, “makes”]);
  wordDistance.shortest(“coding”, “practice”); // 返回 3
  wordDistance.shortest(“makes”, “coding”); // 返回 1

LeetCode 244. 最短单词距离 II
提示:

1 <= wordsDict.length <= 3 * 104
1 <= wordsDict[i].length <= 10
wordsDict[i] 由小写英文字母组成
word1 和 word2 在数组 wordsDict 中
word1 != word2
 shortest 操作次数不大于 5000 

一、解题关键词


二、解题报告

1.思路分析

2.时间复杂度

3.代码示例

class WordDistance {

    Map<String,List<Integer>> map = new HashMap<>();
    public WordDistance(String[] wordsDict) {
        int len = wordsDict.length;
        for(int i = 0;i <len ;i++){
            String word = wordsDict[i];
            map.putIfAbsent(word,new ArrayList<>());
            map.get(word).add(i);
        }

    }
    
    public int shortest(String word1, String word2) {
        List<Integer> index1 = map.get(word1);
        List<Integer> index2 = map.get(word2);
        int size1= index1.size();
        int size2 = index2.size();
        int pos1 = 0;
        int pos2 = 0;
        int ans = Integer.MAX_VALUE;
        while(pos1 < size1 && pos2 < size2){
            int idx1 = index1.get(pos1);
            int idx2 = index2.get(pos2);
            ans = Math.min(ans,Math.abs(idx1 - idx2));
            if(idx1 < idx2){
                pos1++;
            } else{
                pos2++;
            }
        }
        return ans;

    }
}

/**
 * Your WordDistance object will be instantiated and called as such:
 * WordDistance obj = new WordDistance(wordsDict);
 * int param_1 = obj.shortest(word1,word2);
 */ 
 

2.知识点



总结

相同题目

xxx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大涛小先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值