LeetCode Shortest Word Distance
2016-02-11 04:39
525 查看
原题链接在这里:https://leetcode.com/problems/shortest-word-distance/
题目:
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words =
Given word1 =
Given word1 =
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
题解:
Time Complexity: O(n). Space: O(1).
AC Java:
跟上Shortest Word Distance II, Shortest Word Distance III.
题目:
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
For example,
Assume that words =
["practice", "makes", "perfect", "coding", "makes"].
Given word1 =
“coding”, word2 =
“practice”, return 3.
Given word1 =
"makes", word2 =
"coding", return 1.
Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.
题解:
Time Complexity: O(n). Space: O(1).
AC Java:
public class Solution { public int shortestDistance(String[] words, String word1, String word2) { int p1 = -1; int p2 = -1; int res = Integer.MAX_VALUE; for(int i = 0; i<words.length; i++){ if(words[i].equals(word1)){ p1 = i; } if(words[i].equals(word2)){ p2 = i; } if(p1 != -1 && p2 != -1){ res = Math.min(res, Math.abs(p2-p1)); } } return res; } }
跟上Shortest Word Distance II, Shortest Word Distance III.
相关文章推荐
- 51Nod 1305 Pairwise Sum and Divide(规律、数学)
- PowerShell 字符串的几种类型判断
- Java中使用Cookie记录用户访问次数
- 51Nod1381 硬币游戏(概率+题解)
- ng-repeat的group
- 好的学习资源
- 三打白骨精
- 4.6.x IL2CPP问题汇总
- LeetCode Flip Game II
- UNDER THE HOOD OF THE NEW AZURE PORTAL
- QString, string, char* 相互转换
- POJ 3684 Physics Experiment(弹性碰撞)
- LeetCode Flip Game
- hdoj 4405 Aeroplane chess(概率dp)
- 全国计算机等级考试C语言考试程序改错题
- 全国计算机二级考试ACCESS入门教程
- vcs 入门
- hdu1874 最短路模板题
- Linux 学习树之基础20160211
- shell程序设计(三)