原题链接在这里:https://leetcode.com/problems/shortest-word-distance-iii/
题目:
This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.
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.
For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"]
.
Given word1 = “makes”
, word2 = “coding”
, return 1.
Given word1 = "makes"
, word2 = "makes"
, return 3.
题解:
若是两个指针p1 和 p2相等时,不更新res.
Time Complexity: O(n). Space: O(1).
AC Java:
class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
if(words == null){
return -1;
} int ind1 = -1;
int ind2 = -1;
int res = words.length; for(int i = 0; i < words.length; i++){
if(words[i].equals(word1)){
ind1 = i;
if(ind2 != -1){
res = Math.min(res, ind1 - ind2);
}
} if(words[i].equals(word2)){
ind2 = i;
if(ind1 != -1 && ind1 < ind2){
res = Math.min(res, ind2 - ind1);
}
}
} return res;
}
}