程序媛詹妮弗
终身学习

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.

Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Input: word1 = “makes”, word2 = “coding”
Output: 1
Input: word1 = "makes", word2 = "makes"
Output: 3

Note:
You may assume word1 and word2 are both in the list.

 

题意:

和之前[leetcode]243. Shortest Word Distance最短单词距离一样,不过这次俩给定单词可以相同。

 

Solution1: Two Pointers

判断word1是否等于word2

1. 不相等, 照[leetcode]243. Shortest Word Distance最短单词距离 来做

2.  相等, 用pre来track word1出现的index, word2再出现时,更新result

 

code

 1 class Solution {
 2        public int shortestWordDistance(String[] words, String word1, String word2) {
 3         //corner case
 4         if (words == null || words.length == 0) return -1;
 5         if (word1 == null || word2 == null)  return -1;
 6 
 7         boolean isSame = false;
 8 
 9         if (word1.equals(word2))
10             isSame = true;
11 
12         int result = Integer.MAX_VALUE;
13         int prev = -1;
14         int a = -1;
15         int b = -1;
16 
17         for (int i = 0; i < words.length; i++) {
18             if(!isSame){
19                 if (word1.equals(words[i])) {
20                     a = i;
21                 } else if (word2.equals(words[i])) {
22                     b = i;
23                 }
24                 if ( a != -1 && b != -1){
25                     result = Math.min(result, Math.abs(a-b));
26                 }
27             }else{
28                 if (words[i].equals(word1)) {
29                     if (prev != -1) {
30                         result = Math.min(result, i - prev);
31                     }
32                     prev = i;
33                 }
34             }
35         }
36         return result;
37     }
38 }

 

posted on 2019-05-04 06:34  程序媛詹妮弗  阅读(162)  评论(0编辑  收藏  举报