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 }
  • 相关阅读:
    React 之使用 fetch
    react-native 环境搭建
    create-react-app 配置 less
    React新的前端思维方式
    字体图标 —— IconMoon
    你不知道的javascript 之 >>
    前端的自我修养
    jquery 学习
    html的meta总结
    git基本操作 nginx基本操作
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5798952.html
Copyright © 2011-2022 走看看