您的位置:首页 > 其它

【LeetCode】245.Shortest Word Distance III(Medium)(加锁题)解题报告

2018-02-27 21:32 501 查看
【LeetCode】245.Shortest Word Distance III(Medium)(加锁题)解题报告

题目地址:https://leetcode.com/problems/shortest-word-distance-iii/

题目描述:

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

  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.v

  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.

  有重复单词.

Solution:

//time : O(n)
//space : O(1)
class Solution {
public int shortestWordDistance(String[] words, String word1, String word2) {
int res = words.length;
int a = -1;
int b = -1;
for(int i=0 ; i<words.length ; i++){
if(words[i].equals(word1)){
a = i;
}
if(words[i].equals[word2]){
if(word1.equals(word2)){
a = b;
}
b = i;
}
if(a != -1 && b != -1){
res = Math.min(res,Math.abs(a-b));
}
}
return res;
}
}


Date:2018年2月27日
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode array