2ms O(n) Java


  • 0
    Q

    Nothing impressive, don't upvote!

    public class Solution {
        public int shortestDistance(String[] words, String word1, String word2) {
            int metState = 0;
            int index = -1;
            int minDist = Integer.MAX_VALUE;
            for(int i = 0; i < words.length; ++i){
                if(words[i].equals(word1)){
                    if(metState == 2){
                        minDist = (i - index) < minDist ? i- index : minDist;
                    }
                    index = i;
                    metState = 1;
                    continue;
                }
                if(words[i].equals(word2)){
                    if(metState == 1){
                        minDist = (i - index) < minDist ? i- index : minDist;
                    }
                    index = i;
                    metState = 2;
                }
            }
            return minDist;
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.