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;
    }
    

      

      

  • 相关阅读:
    asp.net介绍
    asp.net基本控件
    SQL 查询横表变竖表
    北京北京
    【算法】蓝桥杯dfs深度优先搜索之排列组合总结
    【算法】蓝桥杯dfs深度优先搜索之凑算式总结
    《剑指Offer》面试题3:二维数组中的查找
    《剑指Offer》面试题2:实现Singleton(单例)模式
    《剑指Offer》面试题1:赋值运算符函数
    CentOS6.5x64搭建Hadoop环境
  • 原文地址:https://www.cnblogs.com/apanda009/p/7797157.html
Copyright © 2011-2022 走看看