-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathShortestDistanceToACharacter.java
46 lines (40 loc) · 1.28 KB
/
ShortestDistanceToACharacter.java
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
39
40
41
42
43
44
45
46
package com.smlnskgmail.jaman.leetcodejava.easy;
import java.util.ArrayList;
import java.util.List;
// https://leetcode.com/problems/shortest-distance-to-a-character/
public class ShortestDistanceToACharacter {
private final String string;
private final char character;
public ShortestDistanceToACharacter(
String string,
char character
) {
this.string = string;
this.character = character;
}
public int[] solution() {
int[] result = new int[string.length()];
List<Integer> indexes = new ArrayList<>();
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == character) {
indexes.add(i);
}
}
int pos = 0;
for (int i = 0; i < string.length(); i++) {
int index = indexes.get(pos);
int first = Math.abs(index - i);
if (pos + 1 < indexes.size()) {
int secondIndex = indexes.get(pos + 1);
int second = Math.abs(secondIndex - i);
result[i] = Math.min(first, second);
if (first > second) {
pos++;
}
} else {
result[i] = first;
}
}
return result;
}
}