zoukankan      html  css  js  c++  java
  • Shortest Word Distance III

    This is a follow up of Shortest Word Distance. The only difference is now word1 could be the same as word2.

    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.

    For example,
    Assume that words = ["practice", "makes", "perfect", "coding", "makes"].

    Given word1 = “makes”, word2 = “coding”, return 1.
    Given word1 = "makes", word2 = "makes", return 3.

    Note:
    You may assume word1 and word2 are both in the list.

    Approach: two case:

    1: word1 != word2 , it is simple, some are using i1 = -1, i2 = -1 to check, here I used the distance. Because when checking the min distance, I dont want fake min distance in my result, so I try to expand the initial distance of i1 and i2 be greater than words.length, (but we also cannot use i1 = -1 and i2 = words.length, because the target word might give i2 = 0, then mindistance is 1, which is also fake)

    2: word1 == word2, the question becomes how to find the min distance of the indices of a single word. Such as "make" has indices of 0, 3, 5,xxxxx...how to find the min distance. Just use use current i minus last index and keep the global min value.

    may assume word1 and word2 are both in the list??????

    public int shortestWordDistance(String[] words, String word1, String word2) {
        if (words == null || words.length == 0) return 0;
        int i1 = -words.length;  //here is to guarantee mindistance will be greater than the word.length
        int i2 = words.length;
        int min = Integer.MAX_VALUE;
        for (int i = 0; i < words.length; i++) {
            if (!word1.equals(word2)) {
                if (words[i].equals(word1)) i1 = i;
                if (words[i].equals(word2)) i2 = i;
                min = Math.min(min, Math.abs(i1 - i2)); //so we don't have to check if (i1 != -1 && i2 != -1 in other solutions)
            } else {
                if (words[i].equals(word1)) {  //this the question on how to find the shortest distance of indices of the word
                    min = Math.min(min, Math.abs(i - i1));  //you can change to i - i1, it is also correct
                    i1 = i;  // update the i1 with current i for incoming distance checking
                }
            }
        }
        return min;
    }
    

      

      

  • 相关阅读:
    记一个centos分区大小调整过程
    破解StarUML3.01最新版 for Linux(Ubuntu16LTS)
    为什么我们要使用int类型来保存时间类型的数据。
    sphinx-doc的中文搜索
    ubuntu下file_get_contents返回空字符串
    PSR-PHP开发规范(本文版权归作者:luluyrt@163.com)
    PHP单例模式
    PHP中 PCRE正则表达式模式修饰符“u” 的使用。
    Mysql 插入时间时报错Incorrect datetime value: '' for column 'createtime'
    如何给list清空
  • 原文地址:https://www.cnblogs.com/apanda009/p/7797157.html
Copyright © 2011-2022 走看看