JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

Example: Assume that words = [“practice”, “makes”, “perfect”, “coding”, “makes”].

Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3

Note: You may assume word1 and word2 are both in the list.

Code

class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        int p1 = -1;
        int p2 = -1;

        int min = words.length;

        for(int i = 0; i < words.length; i++) {
            if(words[i].equals(word1)) {
                p1 = i;
            }

            if (words[i].equals(word2)) {
                if(word1.equals(word2)) {
                    p1 = p2;
                }

                p2 = i;
            }

            if(p1 != -1 && p2 != -1) {
                min = Math.min(min, Math.abs(p1 - p2));
            }
        }

        return min;
    }
}
class Solution:
    def shortestWordDistance(self, words: List[str], word1: str, word2: str) -> int:
        if not words or len(words) < 2:
            return -1

        a = -1
        b = -1

        res = float("inf")

        for index, word in enumerate(words):
            if word == word1:
                a = index

            if word == word2:
                if word1 == word2:
                    a = b

                b = index

            if a != -1 and b != -1:
                res = min(res, abs(a - b))

        return res
class Solution:
    def shortestWordDistance(self, words: List[str], word1: str, word2: str) -> int:
        if not words or len(words) < 2:
            return -1

        map = {}
        d = len(words)

        for index, word in enumerate(words):
            if word == word1:
                if word2 in map:
                    d = min(d, index - map[word2])
            if word == word2:
                if word1 in map:
                    d = min(d, index - map[word1])

            map[word] = index

        return d