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.
题目跟leetcode 243很像,只是word1和word2可以相同了。
用p1, p2两个pointer记录word1,word2最后一次出现的位置。最短路径就是所有|p1 - p2|
中的最小值
如果word1跟word2相同,p1指向p2的上一个位置,p2更新为新位置就可以了
代码如下:
|
|
Ref: https://discuss.leetcode.com/topic/20887/12-16-lines-java-c