share my java solution, 3ms


  • 0
    W
    public int shortestWordDistance(String[] words, String word1, String word2) {
        int pos1 = 0;
        int pos2 = 0;
        int len = words.length;
        int res = Integer.MAX_VALUE;
        while(pos2 < len ){
            while(pos2 < len && !word2.equals(words[pos2])) pos2++;
            if(pos2 == len) {
                break;
            }
            pos1 = pos2 - 1;
            while(pos1 >= 0 && !word1.equals(words[pos1])) pos1--;
            if(pos1 >= 0) {
                res = Math.min(res, pos2 - pos1);
            }
            pos1 = pos2 + 1;
            while(pos1 < len && !word1.equals(words[pos1])) pos1++;
            if(pos1 < len) {
                res = Math.min(res, pos1 - pos2);
            }
            pos2++;
        }
        return res;
    }

Log in to reply
 

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