Leetcode: Shortest Word Distance III
2015-12-21 06:40
441 查看
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.
还是采取Shortest Word Distance I 的方法
只不过判断 minDis的时候加入判断,如果 i==j,minDis = minDis
public class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { int minDis = Integer.MAX_VALUE; int i=-1, j=-1; for (int k=0; k<words.length; k++) { if (words[k].equals(word1)) { i = k; if (i!=-1 && j!=-1) minDis = Math.min(minDis, Math.abs(i-j)); } if (words[k].equals(word2)) { j = k; if (i!=-1 && j!=-1) minDis = (i==j)? minDis : Math.min(minDis, Math.abs(i-j)); } } return minDis; } }
相关文章推荐
- UVA 299 Train Swapping
- UVA-152 Tree's a Crowd
- RTTI、虚函数和虚基类的实现方式、开销分析及使用指导(虚函数的开销很小,就2次操作而已)
- 开始一个新的地方作为自己技术的心灵园田,新浪微博太伤我心了
- UVA-10420 List of Conquests
- UVA-340 Master-Mind Hints (猜数字)
- Data URI 应用场景小结
- [leetcode] 22. Generate Parentheses 解题报告
- urllib.urlretrieve()
- Hadoop安装教程_单机/伪分布式配置_Hadoop2.6.0/Ubuntu14.04
- *Reverse Linked List II
- LeetCode - Remove Duplicates from Sorted Array
- C标准库没提供的助手函数:字符串替换
- LeetCode - Reverse Nodes in k-Group
- Leetcode: Shortest Word Distance II
- Android RecyclerView使用详解四
- *Insertion Sort List
- python对文件及文件夹的一些操作
- 二分查找(折半查找)
- 文章标题