【Lintcode】924. Shortest Word Distance

題目地址:

https://www.lintcode.com/problem/shortest-word-distance/description

給定一個字符串數組,再給定兩個單詞,求這兩個單詞在字符串中最小的下標距離(數組中可能含有某個單詞多次)。

用兩個指針記錄兩個單詞出現的位置,然後不斷更新距離即可。代碼如下:

public class Solution {
    /**
     * @param words: a list of words
     * @param word1: a string
     * @param word2: a string
     * @return: the shortest distance between word1 and word2 in the list
     */
    public int shortestDistance(String[] words, String word1, String word2) {
        // Write your code here
        int idx1 = -1, idx2 = -1;
        int res = words.length;
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                idx1 = i;
            }
            if (words[i].equals(word2)) {
                idx2 = i;
            }
            // 如果兩個字符串都找到了,則算一下距離,並更新
            if (idx1 != -1 && idx2 != -1) {
                res = Math.min(res, Math.abs(idx1 - idx2));
            }
        }
        
        return res;
    }
}

時間複雜度O(nl)O(nl),空間O(1)O(1)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章