Shortest Word Distance

class Solution {

public int shortestDistance(String[] words, String word1, String word2) {

if(words == null || words.length == 0){

return -1;

}

int diff = Integer.MAX_VALUE;

int index = -1;

for(int i = 0; i < words.length; i++){

if( words[i].equals(word1) || words[i].equals(word2)){

if(index != -1 && !words[index].equals(words[i])){

diff = Math.min(i - index, diff);

}

index = i;

}

}

return diff;

}

}

你可能感兴趣的:(Shortest Word Distance)