Problem 243

Posted by Ruizhi Ma on November 2, 2020

Solution URL

https://leetcode.com/submissions/detail/416221951/

代码

class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        //ans: Solution
        //Time: O(N)
        //Space: O(1)
        //record most recent index of word1 and word2
        int idx1 = -1;
        int idx2 = -1;
        int dis = words.length;
        //use loop to update idx1 and idx2
        //update the min distance between them
        for(int i = 0; i < words.length; i++){
            if(words[i].equals(word1)){
                idx1 = i;
            }else if(words[i].equals(word2)){
                idx2 = i;
            }

            //update the min distance
            if(idx1 != -1 && idx2 != -1){
                dis = Math.min(Math.abs(idx1 - idx2), dis);
            }
        }

        return dis;
    }
}