zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    需要我们了解的SQL Server阻塞原因与解决方法
    SQL Server应用模式之OLTP系统性能分析
    第一章 scala环境搭建
    IO
    装饰器模式
    java 泛型方法
    文件格式转换
    spring ioc
    深入浅出Java模式设计之模板方法模式
    struts2
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5008948.html
Copyright © 2011-2022 走看看