国产xxxx99真实实拍_久久不雅视频_高清韩国a级特黄毛片_嗯老师别我我受不了了小说

資訊專欄INFORMATION COLUMN

[LeetCode] 243. Shortest Word Distance

高勝山 / 1890人閱讀

Problem

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", "makes"].

Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

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

文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/72709.html

相關(guān)文章

  • [Leetcode] Shortest Word Distance 最短單詞間距

    摘要:代碼第一次寫入就先不比較第一次寫入就先不比較哈希表法復雜度時間空間思路因為會多次調(diào)用,我們不能每次調(diào)用的時候再把這兩個單詞的下標找出來。我們可以用一個哈希表,在傳入字符串數(shù)組時,就把每個單詞的下標找出存入表中。 Shortest Word Distance Given a list of words and two words word1 and word2, return the ...

    jsliang 評論0 收藏0
  • [LeetCode] 244. Shortest Word Distance II

    Problem Design a class which receives a list of words in the constructor, and implements a method that takes two words word1 and word2 and return the shortest distance between these two words in the l...

    Nekron 評論0 收藏0
  • [LeetCode] 245. Shortest Word Distance III

    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 i...

    csRyan 評論0 收藏0
  • [LeetCode] 126. Word Ladder II

    摘要:存放過程中的所有集合為所有的結(jié)尾,則順序存放這個結(jié)尾對應的中的所有存放同一個循環(huán)的新加入的,在下一個循環(huán)再依次對其中元素進行進一步的把首個字符串放入新,再將放入,并將鍵值對放入,進行初始化 Problem Given two words (start and end), and a dictionary, find all shortest transformation sequenc...

    wayneli 評論0 收藏0
  • Leetcode PHP題解--D49 821. Shortest Distance to a Ch

    摘要:返回字符串中每一個字符離給定的字符的最短距離。否則,當當前下標大于上一個出現(xiàn)字符的位置,且存在下一個字符時,距離為兩者中最小的那個。最終代碼若覺得本文章對你有用,歡迎用愛發(fā)電資助。 D49 821. Shortest Distance to a Character 題目鏈接 821. Shortest Distance to a Character 題目分析 給定一個字符串s和一個字符...

    Shisui 評論0 收藏0

發(fā)表評論

0條評論

最新活動
閱讀需要支付1元查看
<