MCPcopy Create free account
hub / github.com/careercup/ctci / shortest

Method shortest

java/Chapter 18/Question18_5/Question.java:7–29  ·  view source on GitHub ↗
(String[] words, String word1, String word2)

Source from the content-addressed store, hash-verified

5public class Question {
6
7 public static int shortest(String[] words, String word1, String word2) {
8 int min = Integer.MAX_VALUE;
9 int lastPosWord1 = -1;
10 int lastPosWord2 = -1;
11 for (int i = 0; i < words.length; i++) {
12 String currentWord = words[i];
13 if (currentWord.equals(word1)) {
14 lastPosWord1 = i;
15 // Comment following 3 lines if word order matters
16 int distance = lastPosWord1 - lastPosWord2;
17 if (lastPosWord2 >= 0 && min > distance) {
18 min = distance;
19 }
20 } else if (currentWord.equals(word2)) {
21 lastPosWord2 = i;
22 int distance = lastPosWord2 - lastPosWord1;
23 if (lastPosWord1 >= 0 && min > distance) {
24 min = distance;
25 }
26 }
27 }
28 return min;
29 }
30
31 public static String wordAtLocation(String[] words, int loc) {
32 if (loc < 0 || loc >= words.length) {

Callers 1

mainMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected