Post

Leetcode - Sortest Word Distance(Premium)

Leetcode - Sortest Word Distance(Premium)

Hits

  • Given an array of strings words and two different strings that already exist in the array word1 and word2, return the shortest distance between these two words in the list.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import (
)

type Solution struct{}

// shortestDistance finds the shortest distance between two words in an array.
func (s *Solution) shortestDistance(words []string, word1 string, word2 string) int {
	firstPosition, secondPosition := -1, -1
	distance := len(words)

	for ind, word := range words{
		if word==word1{
			firstPosition = ind
		}else if word==word2{
			secondPosition = ind
		}

		if firstPosition!=-1 && secondPosition!=-1{

			distance= currentDistance(firstPosition, secondPosition, distance)
		}
	}

	return distance
}

func currentDistance(first, second, distance int)int{
	cD := second-first
	if cD<0{
		cD = (-1)*cD
	}

	if cD < distance{
		return cD
	}
	return distance
}

Problem Statement in DesignGuru

This post is licensed under CC BY 4.0 by the author.