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

  • 相关阅读:
    mapx 32位在win8 64位上使用
    ora01940 无法删除当前连接的用户
    powerdesigner操作
    iis7文件夹 首页设置
    安装vs2013以后,链接数据库总是报内存损坏,无法写入的错误
    【ASP.NET】 中 system.math 函数使用
    Android Bundle类
    android intent 跳转
    vs2012 webservice创建
    Linux中的日志分析及管理
  • 原文地址:https://www.cnblogs.com/yrbbest/p/5008948.html
Copyright © 2011-2022 走看看