首页 > 其他 > 详细

[leetcode]245. Shortest Word Distance III最短单词距离(word1可能等于word2)

时间:2019-05-04 10:13:42      阅读:140      评论:0      收藏:0      [点我收藏+]

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.

 

题意:

和之前一样,不过这次俩单词可以相同。

 

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 }

 

[leetcode]245. Shortest Word Distance III最短单词距离(word1可能等于word2)

原文:https://www.cnblogs.com/liuliu5151/p/10807441.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!