LeetCode 243. Shortest Word Distance

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

题目:

Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

For example,
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

Given word1 = “coding”word2 = “practice”, return 3.
Given word1 = "makes"word2 = "coding", return 1.

Note:
You may assume that word1 does not equal to word2, and word1 and word2 are both in the list.

题解:

Time Complexity: O(n). n = words.length.

Space: O(1).

AC Java:

 1 class Solution {
 2     public int shortestDistance(String[] words, String word1, String word2) {
 3         if(words == null || words.length == 0 || word1.equals(word2)){
 4             return 0;
 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){
22                     res = Math.min(res, ind2 - ind1);
23                 }
24             }
25         }
26         
27         return res;
28     }
29 }

 跟上Shortest Word Distance IIShortest Word Distance III.

posted @ 2016-02-11 04:39  Dylan_Java_NYC  阅读(307)  评论(0编辑  收藏  举报