LeetCode Shortest Word Distance

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

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

AC Java:

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

 跟上Shortest Word Distance II, Shortest Word Distance III.

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