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

    Solution:

    When word1==word2, update both p1 and p2 regularly and compute minDis for each update except when p2 updated and get p2==p1.

     1 public class Solution {
     2     public int shortestWordDistance(String[] words, String word1, String word2) {
     3         if (words.length<2) return -1;
     4     
     5         int p1 = -words.length, p2 = -words.length;
     6         int minDis = Integer.MAX_VALUE;
     7         for (int i=0;i<words.length;i++){
     8             if (!words[i].equals(word1) && !words[i].equals(word2)) continue;
     9 
    10             if (words[i].equals(word1)){
    11                 p1 = i;            
    12                 minDis = Math.min(minDis,Math.abs(p1-p2));
    13             } 
    14             
    15             if (words[i].equals(word2)){
    16                 p2 = i;
    17                 if (p2!=p1) minDis = Math.min(minDis,Math.abs(p1-p2));
    18             }
    19         }
    20         return minDis;
    21     }
    22 }
  • 相关阅读:
    Java中常见时间类的使用
    springboot2.0介绍1
    Element-ui-Basic
    Java开发中的23中设计模式详解(一)工厂方法模式和抽象工厂模式
    CSS3 变形、过渡、动画、关联属性浅析
    Webpack 入门教程
    ES6对象简洁语法
    如何下载ts文件
    PPT转PDF
    python实践
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5798952.html
Copyright © 2011-2022 走看看