LeetCode 245. Shortest Word Distance III

原题链接在这里: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 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.

题解:

若是两个指针p1 和 p2相等时,不更新res. 

Time Complexity: O(n). Space: O(1).

AC Java:

 1 class Solution {
 2     public int shortestWordDistance(String[] words, String word1, String word2) {
 3         if(words == null){
 4             return -1;
 5         }
 6         
 7         int ind1 = -1;
 8         int ind2 = -1;
 9         int res = words.length;
10         
11         for(int i = 0; i < words.length; i++){
12             if(words[i].equals(word1)){
13                 ind1 = i;
14                 if(ind2 != -1){
15                     res = Math.min(res, ind1 - ind2);
16                 }
17             }
18             
19             if(words[i].equals(word2)){
20                 ind2 = i;
21                 if(ind1 != -1 && ind1 < ind2){
22                     res = Math.min(res, ind2 - ind1);
23                 }
24             }
25         }
26         
27         return res;
28     }
29 }

类似Shortest Word Distance

posted @ 2016-02-11 10:16  Dylan_Java_NYC  阅读(225)  评论(0编辑  收藏  举报