LeetCode刷题实战245:最短单词距离 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.
示例
示例:
假设 words = ["practice", "makes", "perfect", "coding", "makes"].
输入: word1 = “makes”, word2 = “coding”
输出: 1
输入: word1 = "makes", word2 = "makes"
输出: 3
注意:
你可以假设 word1 和 word2 都在列表里。
解题
public class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
int idx1 = -1, idx2 = -1, distance = Integer.MAX_VALUE, turn = 0, inc = (word1.equals(word2) ? 1 : 0);
for(int i = 0; i < words.length; i++){
if(words[i].equals(word1) && turn % 2 == 0){
idx1 = i;
if(idx2 != -1) distance = Math.min(distance, idx1 - idx2);
turn += inc;
} else if(words[i].equals(word2)){
idx2 = i;
if(idx1 != -1) distance = Math.min(distance, idx2 - idx1);
turn += inc;
}
}
return distance;
}
}