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

博客围绕计算列表中两个单词的最短距离展开,这两个单词可能相同。介绍了使用双指针的解法,需判断两单词是否相等,若不相等按之前方法处理,若相等则用pre记录单词出现的索引,再出现时更新结果。

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 }

 

转载于:https://www.cnblogs.com/liuliu5151/p/10807441.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值