index1
and index2
to -1, which will hold the most recent positions of word1
and word2
respectively.minDistance
to Integer.MAX_VALUE
to keep track of the shortest distance found so far.wordsDict
array using a variable i
.word1
, update index1
to i
.word2
, update index2
to i
.index1
and index2
are not -1 (meaning both words have been found at least once), update minDistance
with the smaller value between minDistance
and the absolute difference between index1
and index2
.minDistance
as the result.