Shortest Word Distance III

题目
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.

word1 and word2 may be the same and they represent two individual words in the list.

答案

class Solution {
    public int shortestWordDistance(String[] words, String word1, String word2) {
        // Get all possible positions for these two words
        List<Integer> pos1 = new ArrayList<>();
        List<Integer> pos2 = new ArrayList<>();
        int ans = Integer.MAX_VALUE;
        for(int i = 0; i < words.length; i++) {
            if(words[i].equals(word1)) {
                pos1.add(i);
            }
            if(words[i].equals(word2)) {
                pos2.add(i);
            }
        }

        // For each pair of position (i, j), record min(abs(i - j))
        for(int i = 0; i < pos1.size(); i++) {
            for(int j = 0; j < pos2.size(); j++) {
                if(pos1.get(i).intValue() == pos2.get(j).intValue()) continue;
                //System.out.println(Integer.toString(pos1.get(i)) + ' ' + Integer.toString(pos1.get(j)));

                ans = Math.min(ans, Math.abs(pos1.get(i) - pos2.get(j)));
            }
        }
        return ans;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容