Straight-forward Java solution derived from shortest word distance i


  • 0
    Q
    public class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        //Decide whether word1 is different with word2
        if (words == null || words.length == 0) {
            return 0;
        }
        int firstposition = -1;
        int secondposition = -1;
        int len = Integer.MAX_VALUE;
        if (word1.equals(word2)) {
            for (int i = 0; i < words.length; i++) {
                if (words[i].equals(word1)) {
                    if (firstposition == -1) {
                        firstposition = i;
                    } else if (secondposition == -1) {
                        secondposition = i;
                    } else {
                        len = Math.min(i - Math.max(firstposition, secondposition), len);
                        if (Math.max(firstposition,secondposition) == firstposition) {
                            secondposition = i;
                        } else {
                            firstposition = i;
                        }
                    }
                }
                if (firstposition != -1 && secondposition != -1) {
                    len = Math.min(len, Math.abs(secondposition - firstposition));
                }
            }
        } else {
            for (int i = 0; i < words.length; i++) {
                if (words[i].equals(word1)) {
                    firstposition = i;
                }
                if (words[i].equals(word2)) {
                    secondposition = i;
                }
                if (firstposition != -1 && secondposition != -1) {
                    len = Math.min(len, Math.abs(secondposition - firstposition));
                }
            }
        }
        return len;
    }
    

    }


Log in to reply
 

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