-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShortestDistanceToChar.java
More file actions
44 lines (31 loc) · 962 Bytes
/
Copy pathShortestDistanceToChar.java
File metadata and controls
44 lines (31 loc) · 962 Bytes
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
package LeetcodePractice;
import java.util.Arrays;
public class ShortestDistanceToChar {
public static int[] shortestToChar(String s, char c) {
int n = s.length();
int[] answer = new int[n];
int prev = -n;
for (int i = 0; i < n; i++) {
if (s.charAt(i) == c) {
prev = i;
}
answer[i] = i - prev;
}
prev = 2 * n;
for (int i = n - 1; i >= 0; i--) {
if (s.charAt(i) == c) {
prev = i;
}
answer[i] = Math.min(answer[i], prev - i);
}
return answer;
}
public static void main(String[] args) {
String s1 = "loveleetcode";
char c1 = 'e';
System.out.println(Arrays.toString(shortestToChar(s1, c1)));
String s2 = "aaab";
char c2 = 'b';
System.out.println(Arrays.toString(shortestToChar(s2, c2)));
}
}