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.

 

这道题还是让我们求最短单词距离,有了之前两道题Shortest Word Distance IIShortest Word Distance的基础,就大大降低了题目本身的难度。这道题增加了一个条件,就是说两个单词可能会相同,所以在第一题中的解法的基础上做一些修改,我最先想的解法是基于第一题中的解法二,由于会有相同的单词的情况,那么p1和p2就会相同,这样结果就会变成0,显然不对,所以我们要对word1和word2是否的相等的情况分开处理,如果相等了,由于p1和p2会相同,所以我们需要一个变量t来记录上一个位置,这样如果t不为-1,且和当前的p1不同,我们可以更新结果,如果word1和word2不等,那么还是按原来的方法做

public class WordDistance {
    public static int shortestWordDistance(String[] words, String word1, String word2) {
        int p1 = -1, p2 = -1, dist = Integer.MAX_VALUE;
        for (int i = 0; i < words.length; i++) {
            int t = p1;
            if (words[i] == word1) {
                p1 = i;
            }
            
            if (words[i] == word2) {
                p2 = i;
            }
            if (p1 != -1 && p2 != -1) {
                if (word1 == word2 && t != -1 && p1 != t) {
                    dist = Math.min(dist, Math.abs(t - p1));
                } else if (p1 != p2) {
                    dist = Math.min(dist, Math.abs(p2 - p1));
                }
            }
        }
        return dist;
    }
    
    public static void main(String[] args) {
        String[] words = new String[] {"practice", "makes", "perfect", "coding", "makes"};
        System.out.print(shortestWordDistance(words, "makes", "makes"));
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值