java 243.最短字距(#)。java

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 243.最短字距(#)。java相关的知识,希望对你有一定的参考价值。

public class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        if (words == null || words.length == 0 || word1 == null || word2 == null) {
            return 0;
        }
        
        int min = Integer.MAX_VALUE;
        int index = -1;
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1) || words[i].equals(word2)) {
                if (index != -1 && !words[index].equals(words[i])) {
                    min = Math.min(min, i - index);
                }
                index = i;
            }
        }
        
        return min;
    }
}
public class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        if (words == null || words.length == 0 || word1 == null || word2 == null) {
            return 0;
        }
        
        int min = Integer.MAX_VALUE;
        
        for (int i = 0; i < words.length; i++) {
            if (words[i].equals(word1)) {
                min = Math.min(expand(word2, i, words), min);
            }
        }
        
        return min;
    }
    
    public int expand(String word2, int i, String[] words) {
        for (int j = 1; j < words.length; j++) {
            int index1 = i + j;
            int index2 = i - j;
            
            if (index1 < words.length) {
                if (word2.equals(words[index1])) {
                    return j;
                }
            }
            
            if (index2 >= 0) {
                if (word2.equals(words[index2])) {
                    return j;
                }
            }
        }
        
        return 0;
    }
}
public class Solution {
    public int shortestDistance(String[] words, String word1, String word2) {
        if (words == null || words.length < 1) return -1;
        int len = words.length;
        Map<String, List<Integer>> map = new HashMap<>();
        for (int i = 0; i < len; i++) {
            map.putIfAbsent(words[i], new ArrayList<Integer>());
            map.get(words[i]).add(i);
        }
        int distance = Integer.MAX_VALUE;
        for (int i : map.get(word1)) {
            for (int j : map.get(word2)) {
                distance = Math.min(distance, Math.abs(i - j));
            }
        }
        return distance;
    }
}

以上是关于java 243.最短字距(#)。java的主要内容,如果未能解决你的问题,请参考以下文章

java 243.最短字距(#)。java

java 243.最短字距(#)。java

java 243.最短字距(#)。java

java 243.最短字距(#)。java

java 243.最短字距(#)。java

java 243.最短字距(#)。java