• 245. 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.

    链接: http://leetcode.com/problems/shortest-word-distance-iii/

    题解:

    也是Shortest word distance的follow up。这回两数可以一样。 在遍历的时候我们可以多写一个分支。 或者更简化的话可以把两个分支合并起来。

    Time Complexity - O(n), Space Complexity - O(1)

    public class Solution {
        public int shortestWordDistance(String[] words, String word1, String word2) {
            if(words == null || words.length == 0 || word1 == null || word2 == null)
                return 0;
            int minDistance = Integer.MAX_VALUE, word1Index = -1, word2Index = -1;
            boolean isWord1EqualsWord2 = word1.equals(word2);
            
            for(int i = 0; i < words.length; i++) {
                if(isWord1EqualsWord2) {
                    if(words[i].equals(word1)) {
                        if(word1Index >= 0)
                            minDistance = Math.min(minDistance, i - word1Index);
                        word1Index = i;
                    }
                } else {
                    if(words[i].equals(word1))
                        word1Index = i;
                    if(words[i].equals(word2))
                        word2Index = i;
                    if(word1Index >= 0 && word2Index >= 0)
                        minDistance = Math.min(minDistance, Math.abs(word2Index - word1Index));    
                }
            }
            
            return minDistance;
        }
    }

    Reference:

    https://leetcode.com/discuss/50360/my-concise-java-solution

    https://leetcode.com/discuss/50715/12-16-lines-java-c

  • 相关阅读:
    Linux PHP连接MSSQL
    Curl参数一览
    [android开发必备] Android开发者社区汇总
    android定时器
    一个mysql小技巧
    php empty问题
    周报_2012第16周(2012/04/152012/04/21)
    周报_2012第17周(2012/04/222012/04/28)
    周报_2013第04周(2013/01/202013/01/26)
    周报_2013第01周(2012/12/302012/01/05)
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5008948.html
Copyright © 2020-2023  润新知