您的位置:首页 > 其它

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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: