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

  • 相关阅读:
    前端开源项目周报0408
    iOS开源项目周报0406
    安卓开源项目周报0405
    iOS开源项目周报0330
    安卓开源项目周报0329
    前端开源项目周报0328
    vue项目搭建
    微信中h5页面用window.history.go(-1)返回上一页页面不会重新加载问题
    h5移动端页面meta标签
    js中break跳出多层循环
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5008948.html
Copyright © 2011-2022 走看看