AC Java Solution. Self Explanatory.

  • 0
    public class Solution {
        public int shortestDistance(String[] words, String word1, String word2) {
            int min = Integer.MAX_VALUE;
            int i=-1,j=-1,k=0;
            while(k < words.length) {
                if(words[k].equals(word1)) i=k;
                if(words[k].equals(word2)) j=k;
                if(i!=-1&&j!=-1) min = (min>Math.abs(i-j))?Math.abs(i-j):min;
            return min;

Log in to reply

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