字符串數組中兩個字符的最短距離

[leetcode] https://leetcode.com/problems/shortest-word-distance/ java

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

Given word1 = 「coding」word2 = 「practice」, return 3.
Given word1 = "makes"word2 = "coding", return 1.spa

須要注意:code

  1. 該數組中得字符串有可能出現屢次,好比例子中的makes;orm

這個問題比較簡單,按照下面的步驟能夠簡單的作出來:leetcode

  1. 記錄給定兩個字符串出現的位置,會獲得兩個數組;假設爲a和b;字符串

  2. 而後計算abs(a[i] - b[j])的最小值便可;get

第一步掃描一遍字符串數組便可;第二步,若是簡單的用兩層循環來作,由於a和b的長度都有多是n(好比各佔一半),那麼用O(n * n)的時間;it

事實上,有意思的地方就在於,第二步能夠在線性時間內解出來;這裏有一個隱藏的特性,掃描原數組的時候獲得的兩個字符的位置數組,是有序的;好比數組 [a, b, a, b, b, a], 那麼a的位置數組爲[0, 2, 5], b的爲[1, 3, 4]; 假設咱們比較到了位置2和位置3,咱們是沒有必要去比較位置2和4的;由於後者的距離確定大於前者;用下面的圖可能更清楚;class

因此,能夠獲得這樣的關係,當a < b的時候,增長a的座標,當a > b的時候,增長b的座標;這樣就能夠在o(n)的時間內完成;

public int shortestDistance(String[] words, String word1, String word2) {
    int[] indexes1 = new int[words.length];
    int[] indexes2 = new int[words.length];
    int m = 0, n = 0;
    for (int i = 0; i < words.length; i++) {
        String word = words[i];
        if (word.equals(word1)) {
            indexes1[m++] = i;
        } else if (word.equals(word2)) {
            indexes2[n++] = i;
        }
    }
    int dist = Integer.MAX_VALUE;

    for (int i = 0, j = 0; i < m && j < n; ) {
        int x = indexes1[i];
        int y = indexes2[j];
        dist = Math.min(dist, Math.abs(x - y));
        if (x < y) {
            i++;
        } else {
            j++;
        }
    }

    return dist;
}
相關文章
相關標籤/搜索