[LeetCode] 243. Shortest Word Distance 最短单词距离

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

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “coding”word2 = “practice”, return 3.
Given word1 = "makes"word2 = "coding", return 1.

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

给一个单词数组和两个单词,返回这两个单词在数组里的最短距离。假定两个单词不同,而且都在数组中。

Java:

public int shortestDistance(String[] words, String word1, String word2) {
   int m=-1;
   int n=-1;

   int min = Integer.MAX_VALUE;

   for(int i=0; i<words.length; i++){
        String s = words[i];
        if(word1.equals(s)){
            m = i;
            if(n!=-1)
                min = Math.min(min, m-n);
        }else if(word2.equals(s)){
            n = i;
            if(m!=-1)
                min = Math.min(min, n-m);
        }
   }

   return min;
}  

Python:

# Time:  O(n)
# Space: O(1)

class Solution:
    # @param {string[]} words
    # @param {string} word1
    # @param {string} word2
    # @return {integer}
    def shortestDistance(self, words, word1, word2):
        dist = float("inf")
        i, index1, index2 = 0, None, None
        while i < len(words):
            if words[i] == word1:
                index1 = i
            elif words[i] == word2:
                index2 = i

            if index1 is not None and index2 is not None:
                dist = min(dist, abs(index1 - index2))
            i += 1

        return dist

C++:

class Solution {
public:
    int shortestDistance(vector<string>& words, string word1, string word2) {
        int p1 = -1, p2 = -1, res = INT_MAX;
        for (int i = 0; i < words.size(); ++i) {
            if (words[i] == word1) p1 = i;
            else if (words[i] == word2) p2 = i;
            if (p1 != -1 && p2 != -1) res = min(res, abs(p1 - p2));
        }
        return res;
    }
};

C++:

class Solution {
public:
    int shortestDistance(vector<string>& words, string word1, string word2) {
        int idx = -1, res = INT_MAX;
        for (int i = 0; i < words.size(); ++i) {
            if (words[i] == word1 || words[i] == word2) {
                if (idx != -1 && words[idx] != words[i]) {
                    res = min(res, i - idx);
                }
                idx = i;
            }
        }
        return res;
    }
};

类似题目:

[LeetCode] 244. Shortest Word Distance II 最短单词距离 II

[LeetCode] 245. Shortest Word Distance III 最短单词距离 III

原文地址:https://www.cnblogs.com/lightwindy/p/9736289.html

时间: 2024-08-24 05:40:23

[LeetCode] 243. Shortest Word Distance 最短单词距离的相关文章

[LeetCode] 244. Shortest Word Distance II 最短单词距离 II

This is a follow up of Shortest Word Distance. The only difference is now you are given the list of words and your method will be called repeatedly many times with different parameters. How would you optimize it? Design a class which receives a list

245. Shortest Word Distance III 单词可以重复的最短单词距离

[抄题]: 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&q

Leetcode solution 243: Shortest Word Distance

Problem Statement Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. Example: Assume that words = ["practice", "makes", "perfect", "coding", "

[Swift]LeetCode243.最短单词距离 $ Shortest Word Distance

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list. For example,Assume that words = ["practice", "makes", "perfect", "coding", "makes"]. G

[LeetCode] Rearrange String k Distance Apart 按距离为k隔离重排字符串

Given a non-empty string str and an integer k, rearrange the string such that the same characters are at least distance k from each other. All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empt

LeetCode OJ:Word Pattern(单词模式)

Given a pattern and a string str, find if str follows the same pattern. Here follow means a full match, such that there is a bijection between a letter in pattern and a non-empty word in str. Examples: pattern = "abba", str = "dog cat cat d

LeetCode | 1385. Find the Distance Value Between Two Arrays两个数组间的距离值【Python】

LeetCode 1385. Find the Distance Value Between Two Arrays两个数组间的距离值[Easy][Python][暴力] Problem LeetCode Given two integer arrays arr1 and arr2, and the integer d, return the distance value between the two arrays. The distance value is defined as the nu

来自百度贴吧的练习题 :求最长单词的长度和最短单词的长度。

In the function ex5 write code that will input a line of text, split it into words, and display these words one per line, and also print the length of the longest and shortest words. You should regard any sequence of consecutive non-space characters

统计语句中的最长最短单词

已知 string sentence="We were her pride of 10 she named us: Benjamin, Phoenix, the Pordigal and perspicacious pacific Suzanne.";编写程序,计算sentence中有多少个单次,并指出其中最长和最短的单词,如果有多个,则将它们全部输出 使用find_first_of 和find_first_not_of,寻找到单词的起始位置: 使用vector存放最长和最短单词:通过