今天和大家聊的问题叫做 最短单词距离III,我们先来看题面:https://leetcode-cn.com/problems/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.
给定一个单词列表和两个单词 word1 和 word2,返回列表中这两个单词之间的最短距离。word1 和 word2 是有可能相同的,并且它们将分别表示为列表中两个独立的单词。
示例
示例: 假设 words = ["practice", "makes", "perfect", "coding", "makes"]. 输入: word1 = “makes”, word2 = “coding” 输出: 1 输入: word1 = "makes", word2 = "makes" 输出: 3 注意: 你可以假设 word1 和 word2 都在列表里。
解题
这题和I是一样的,唯一不同的是对于word1和word2相同的时候,我们要区分第一次遇到和第二次遇到这个词。这里加入了一个turns,如果是相同单词的话,每次遇到一个单词turn加1,这样可以根据turn来判断是否要switch。
public class Solution { public int shortestWordDistance(String[] words, String word1, String word2) { int idx1 = -1, idx2 = -1, distance = Integer.MAX_VALUE, turn = 0, inc = (word1.equals(word2) ? 1 : 0); for(int i = 0; i < words.length; i++){ if(words[i].equals(word1) && turn % 2 == 0){ idx1 = i; if(idx2 != -1) distance = Math.min(distance, idx1 - idx2); turn += inc; } else if(words[i].equals(word2)){ idx2 = i; if(idx1 != -1) distance = Math.min(distance, idx2 - idx1); turn += inc; } } return distance; } }
好了,今天的文章就到这里,如果觉得有所收获,请顺手点个在看或者转发吧,你们的支持是我最大的动力 。