LeetCode 245. Shortest Word Distance III (最短单词距离之三) $

本文解析了LeetCode上的244题——求两个单词间的最短距离,特别考虑了两个单词可能相同的情况。提供了详细的解决方案及Java实现代码。

This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

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.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “makes”word2 = “coding”, return 1.
Given word1 = "makes"word2 = "makes", return 3.

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

 


题目标签:Array

  题目给了我们一个words array, word1 和word2, 让我们找到word1 和word2 之间最小距离。相比于 243. Shortest Word Distance, 这一题的区别就是,两个word 可能会相等。在243 code的基础上,稍微改一下就可以了。

  因为如果当两个word 是相等的话,那么 不管出现的是word1 还是word2,  在比较words[i] 与 word1 的时候 都会是true,所以只要在这个情况里面 多加一个条件 -> 当 两个word 相等,并且 当前word 是至少第二个word1 的时候,记录它们的距离。

  因为永远到不了else if, 所以p2 永远是 -1, 那么最后一个if 也永远不会进入。

  当两个word 不相等的话,就和243题一样,具体看code。

 

  一直想问,那么这一题的 之二 去哪里了?  怎么只有1 和3 呢?

 

Java Solution:

Runtime beats 46.30% 

完成日期:09/08/2017

关键词:Array

关键点:当两个word相同时候,进入特别条件

 

 1 class Solution 
 2 {
 3     public int shortestWordDistance(String[] words, String word1, String word2) 
 4     {
 5         int p1 = -1, p2 = -1, min = Integer.MAX_VALUE;
 6         boolean same = word1.equals(word2);
 7         
 8         for(int i=0; i<words.length; i++)
 9         {
10             if(words[i].equals(word1)) // if find word1, mark its position
11             {
12                 if(same && p1 != -1) // if two words are same and found a word before
13                     min = Math.min(min, Math.abs(i - p1));
14                 
15                 p1 = i;
16             }
17             else if(words[i].equals(word2)) // if find word2, mark its position
18                 p2 = i;
19             
20             
21             if(p1 != -1 && p2 != -1) // if find word1 and word2, save the smaller distance
22                 min = Math.min(min, Math.abs(p1 - p2));
23         }
24         
25         return min;
26     }
27 }

参考资料:N/A

 

LeetCode 算法题目列表 - LeetCode Algorithms Questions List

 

转载于:https://www.cnblogs.com/jimmycheng/p/7497051.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值