LeetCode 243. 最短单词距离
题目描述
;给定一个字符串数组 wordDict 和两个已经存在于该数组中的不同的字符串 word1 和 word2 。返回列表中这两个单词之间的最短距离。
&emsp&emsp示例 1:
&emsp&emsp输入: wordsDict = [“practice”, “makes”, “perfect”, “coding”, “makes”], word1 = “coding”, word2 = “practice”
&emsp&emsp输出: 3
来源:力扣(LeetCode)
链接:
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
提示:
1 <= wordsDict.length <= 3 * 104
1 <= wordsDict[i].length <= 10
wordsDict[i] 由小写英文字母组成
word1 和 word2 在 wordsDict 中
word1 != word2
一、解题关键词
二、解题报告
1.思路分析
记录下标位置
2.时间复杂度
3.代码示例
class Solution {
public int shortestDistance(String[] wordsDict, String word1, String word2) {
int len = wordsDict.length;
int index1 = -1;
int index2 = -1;
int res = len;
for(int i = 0; i < len;i++){
String word = wordsDict[i];
if(word.equals(word1))index1 = i;
else if(word.equals(word2)) index2 = i;
if(index1 >= 0 && index2 >=0) res = Math.min(res,Math.abs(index1 - index2));
}
return res;
}
}
2.知识点