• 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 }
  • 相关阅读:
    nginx申请并配置免费https
    linux安装git
    linux安装openssl
    nginx配置支持http2
    linux服务器升级nginx
    linux 增加虚拟内存swap(使用文件)
    使用shell安装lnmp
    mysql 数据库主从同步
    Android四大组件之Service
    Android四大组件之Activity
  • 原文地址:https://www.cnblogs.com/lishiblog/p/5798952.html
Copyright © 2020-2023  润新知