Java one pass and update if word kind change. / T : O(N), S : O(1)


  • 0
    J
    public int shortestDistance(String[] words, String word1, String word2) {
            int turn = -1; // -1:Nothing, 0:word1, 1:word2
            int pre = -1;
            int result = Integer.MAX_VALUE;
            for(int i = 0; i < words.length; i++){
                String word = words[i];
                boolean word1Eq = word.equals(word1);
                boolean word2Eq = word.equals(word2);
                if(word1Eq || word2Eq){
                    int nextTurn = word1Eq ? 0 : 1;
                    if(turn != nextTurn && turn != -1){
                        result = ((i - pre) < result) ? (i - pre) : result;
                    }
                    turn = nextTurn;
                    pre = i;
                }
            }
            return result;
        }
    

Log in to reply
 

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