1. 程式人生 > >[leetcode]245. Shortest Word Distance III最短單詞距離(word1可能等於word2)

[leetcode]245. Shortest Word Distance III最短單詞距離(word1可能等於word2)

可能 ger html url integer ref str rdquo 技術分享

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.

題意:

和之前一樣,不過這次倆單詞可以相同。

Solution1: Two Pointers

判斷word1是否等於word2

1. 不相等, 照[leetcode]243. Shortest Word Distance最短單詞距離 來做

技術分享圖片

2. 相等, 用pre來track word1出現的index, word2再出現時,更新result

技術分享圖片

code

 1 class Solution {
 2        public int shortestWordDistance(String[] words, String word1, String word2) {
 3         //corner case
 4         if (words == null || words.length == 0) return -1;
 5         if (word1 == null || word2 == null)  return -1;
 6 
 7         boolean isSame = false
; 8 9 if (word1.equals(word2)) 10 isSame = true; 11 12 int result = Integer.MAX_VALUE; 13 int prev = -1; 14 int a = -1; 15 int b = -1; 16 17 for (int i = 0; i < words.length; i++) { 18 if(!isSame){ 19 if (word1.equals(words[i])) { 20 a = i; 21 } else if (word2.equals(words[i])) { 22 b = i; 23 } 24 if ( a != -1 && b != -1){ 25 result = Math.min(result, Math.abs(a-b)); 26 } 27 }else{ 28 if (words[i].equals(word1)) { 29 if (prev != -1) { 30 result = Math.min(result, i - prev); 31 } 32 prev = i; 33 } 34 } 35 } 36 return result; 37 } 38 }

[leetcode]245. Shortest Word Distance III最短單詞距離(word1可能等於word2)