2015年11月4日星期三

Leetcode 245 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.
Note:
You may assume word1 and word2 are both in the list.
Solution 1: simple use two scenarios: equal and not equal.
 public class Solution {  
   public int shortestWordDistance(String[] words, String word1, String word2) {  
     int n=words.length, res=Integer.MAX_VALUE;  
     if (word1.equals(word2)) {  
       int pre=-1;  
       for (int i=0; i<n; i++) {  
         if (words[i].equals(word1)) {  
           if (pre>=0) res=Math.min(res,i-pre);  
           pre=i;  
         }  
       }  
     }  
     else {  
       int pre1=-1, pre2=-1;  
       for (int i=0; i<n; i++) {  
         if (words[i].equals(word1)) pre1=i;  
         else if (words[i].equals(word2)) pre2=i;  
         else continue;  
         if (pre1>=0 && pre2>=0) res=Math.min(res,Math.abs(pre1-pre2));  
       }  
     }  
     return res;  
   }  
 }  

没有评论:

发表评论