leetcode243. 最短单词距离(vip题)好像挺简单?

栏目: IT技术 · 发布时间: 6年前

内容简介:给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。示例:假设 words = ["practice", "makes", "perfect", "coding", "makes"]

给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。

示例:

假设 words = ["practice", "makes", "perfect", "coding", "makes"]

输入: word1 = “coding”, word2 = “practice”

输出: 3

输入: word1 = "makes", word2 = "coding"

输出: 1

注意:

你可以假设 word1 不等于 word2, 并且 word1 和 word2 都在列表里。

思路:遍歷一遍字符串,记录最后一次出现的位置即可,然后找出差距最小的。

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        int i1 = -1, i2 = -1;
        int minDistance = words.length;
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                i1 = i;
                if (i1 != -1 && i2 != -1 && i1-i2<minDistance)minDistance=i1-i2;
            } else if (words[i].equals(word2)) {
                i2 = i;
                if (i1 != -1 && i2 != -1 && i2-i1<minDistance)minDistance=i2-i1;
            }
        }
        return minDistance;
    }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Squid: The Definitive Guide

Squid: The Definitive Guide

Duane Wessels / O'Reilly Media / 2004 / $44.95 US, $65.95 CA, £31.95 UK

Squid is the most popular Web caching software in use today, and it works on a variety of platforms including Linux, FreeBSD, and Windows. Squid improves network performance by reducing the amount of......一起来看看 《Squid: The Definitive Guide》 这本书的介绍吧!

随机密码生成器
随机密码生成器

多种字符组合密码

MD5 加密
MD5 加密

MD5 加密工具

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器