short line code, java beats 99.9%


  • 0
    R
    public class Solution {
        public int shortestDistance(String[] words, String word1, String word2) {
            int dis = words.length - 1;
            for(int i = 0; i < words.length; i++) {
                if(words[i].equals(word1)) {
                    for(int j = Math.max(i - dis, 0); j < Math.min(i + dis, words.length); j++) {
                        if(words[j].equals(word2)) dis = Math.min(dis, Math.abs(i - j));
                    }
                }
            }
            return dis;
        }
    }
    ``

Log in to reply
 

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