LeetCode 245. 最短单词距离 III

本文详细介绍了LeetCode245题目的解题思路和解决方案,给出了Java代码实现,重点讲解了如何找到两个给定单词在字符串数组中的最短距离。无论是单词相同还是不同,都提供了相应的处理策略,时间复杂度分析以及代码优化。适合准备面试和提升算法能力的读者阅读。

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

LeetCode 245. 最短单词距离 III

题目描述

;给定一个字符串数组 wordsDict 和两个字符串 word1 和 word2 ,返回列表中这两个单词之间的最短距离。
注意:word1 和 word2 是有可能相同的,并且它们将分别表示为列表中 两个独立的单词 。
&emsp&emsp示例 1:
&emsp&emsp输入:wordsDict = [“practice”, “makes”, “perfect”, “coding”, “makes”], word1 = “makes”, word2 = “coding”
&emsp&emsp输出:1

LeetCode 245. 最短单词距离 III
提示:

1 <= wordsDict.length <= 105
1 <= wordsDict[i].length <= 10
wordsDict[i] 由小写英文字母组成
word1 和 word2 都在 wordsDict 中

一、解题关键词


二、解题报告

1.思路分析

2.时间复杂度

3.代码示例

class Solution {
    public int shortestWordDistance(String[] wordsDict, String word1, String word2) {
        int len = wordsDict.length;
        int ans = len;
        if(word1.equals(word2)){
            int prev = -1;
            for(int i = 0; i < len;++i ){
                String word = wordsDict[i];
                if(word.equals(word1)){
                    if(prev >= 0){
                        ans = Math.min(ans,i - prev);
                    }
                     prev = i;
                }
            }
        }else{
            int index1 = -1,index2 = -1;
            for(int i = 0;i < len;i++){
                String word = wordsDict[i];
                if(word.equals(word1))index1 = i;
                else if(word.equals(word2)) index2 = i;
                if(index1 >= 0 && index2 >= 0) ans = Math.min(ans,Math.abs(index1 - index2));
            }
        }
        return ans;
    }
}

2.知识点



总结

相同题目

xxx

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

大涛小先生

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

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

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

打赏作者

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

抵扣说明:

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

余额充值