LeetCode Shortest Word Distance III

原题链接在这里:https://leetcode.com/problems/shortest-word-distance-iii/

类似Shortest Word Distance.

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

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

AC Java:

 1 public class Solution {
 2     public int shortestWordDistance(String[] words, String word1, String word2) {
 3         int p1 = -1;
 4         int p2 = -1;
 5         int res = Integer.MAX_VALUE;
 6         
 7         for(int i = 0; i<words.length; i++){
 8             if(words[i].equals(word1)){
 9                 p1 = i;
10                 if(p1 != -1 && p2 != -1){
11                     res = p1 == p2 ? res : Math.min(res,Math.abs(p1-p2));
12                 }
13             }
14             if(words[i].equals(word2)){
15                 p2 = i;
16                 if(p1 != -1 && p2 != -1){
17                     res = p1 == p2 ? res : Math.min(res,Math.abs(p1-p2));
18                 }
19             }
20         }
21         return res;
22     }
23 }

 

你可能感兴趣的:(LeetCode Shortest Word Distance III)