题目地址:
https://www.lintcode.com/problem/shortest-word-distance/description
给定一个字符串数组,再给定两个单词,求这两个单词在字符串中最小的下标距离(数组中可能含有某个单词多次)。
用两个指针记录两个单词出现的位置,然后不断更新距离即可。代码如下:
public class Solution {
/**
* @param words: a list of words
* @param word1: a string
* @param word2: a string
* @return: the shortest distance between word1 and word2 in the list
*/
public int shortestDistance(String[] words, String word1, String word2) {
// Write your code here
int idx1 = -1, idx2 = -1;
int res = words.length;
for (int i = 0; i < words.length; i++) {
if (words[i].equals(word1)) {
idx1 = i;
}
if (words[i].equals(word2)) {
idx2 = i;
}
// 如果两个字符串都找到了,则算一下距离,并更新
if (idx1 != -1 && idx2 != -1) {
res = Math.min(res, Math.abs(idx1 - idx2));
}
}
return res;
}
}
时间复杂度 O ( n l ) O(nl) O(nl),空间 O ( 1 ) O(1) O(1)。