栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

LeetCode 244. 最短单词距离 II

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

LeetCode 244. 最短单词距离 II

LeetCode 244. 最短单词距离 II

文章目录
  • LeetCode 244. 最短单词距离 II
  • 题目描述
  • 一、解题关键词
  • 二、解题报告
    • 1.思路分析
    • 2.时间复杂度
    • 3.代码示例
    • 2.知识点
  • 总结
  • 相同题目

题目描述

请设计一个类,使该类的构造函数能够接收一个字符串数组。然后再实现一个方法,该方法能够分别接收两个单词,并返回列表中这两个单词之间的最短距离。实现 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> map = new HashMap<>();
    public WordDistance(String[] wordsDict) {
        int len = wordsDict.length;
        for(int i = 0;i 
            String word = wordsDict[i];
            map.putIfAbsent(word,new ArrayList<>());
            map.get(word).add(i);
        }

    }
    
    public int shortest(String word1, String word2) {
        List index1 = map.get(word1);
        List 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;

    }
}

 
 
2.知识点
 

总结 相同题目

xxx

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/937336.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号