[JAVA] Add condition for same word / T : O(N), S : O(1)


  • 0
    J
    class Solution {
        public int shortestWordDistance(String[] words, String word1, String word2) {
            int i1 = -1;
            int i2 = -1;
            int min = Integer.MAX_VALUE;
            boolean change = false;
            for(int i = 0; i < words.length; i++) {
                if(word1.equals(words[i])){
                    // if equal
                    if(word1.equals(word2)){
                        if(change) i1 = i;
                        else i2 = i;
                        change = !change;
                    }
                    else
                        i1 = i;
                }
                else if(word2.equals(words[i])){
                    i2 = i;
                }
                
                if(i1 != -1 && i2 != -1)
                    min = Math.min(Math.abs(i1-i2), min);
            }
            return min;
        }
    }
    

Log in to reply
 

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