• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

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.

还是采取Shortest Word Distance I 的方法

只不过判断 minDis的时候加入判断,如果 i==j,minDis = minDis

 1 public class Solution {
 2     public int shortestWordDistance(String[] words, String word1, String word2) {
 3         int minDis = Integer.MAX_VALUE;
 4         int i=-1, j=-1;
 5         for (int k=0; k<words.length; k++) {
 6             if (words[k].equals(word1)) {
 7                 i = k;
 8                 if (i!=-1 && j!=-1) 
 9                     minDis = Math.min(minDis, Math.abs(i-j));
10             }
11             if (words[k].equals(word2)) {
12                 j = k;
13                 if (i!=-1 && j!=-1) 
14                     minDis = (i==j)? minDis : Math.min(minDis, Math.abs(i-j));
15             }
16         }
17         return minDis;
18     }
19 }

 

posted @ 2015-12-21 06:40  neverlandly  阅读(281)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3