-
Notifications
You must be signed in to change notification settings - Fork 277
/
Copy pathShortestDistancetoaCharacter.java
53 lines (42 loc) · 1.27 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
47
48
49
50
51
52
53
class Solution {
// TC : O(n)
// SC: O(n)
public int[] shortestToChar(String s, char c) {
int len = s.length();
int[] leftDis = new int[len];
int[] rightDis =new int[len];
Arrays.fill(leftDis, Integer.MAX_VALUE);
Arrays.fill(rightDis, Integer.MAX_VALUE);
int runningDis = Integer.MAX_VALUE;
//left to right direction
for(int i=0;i<len;i++){
if(s.charAt(i) == c){
runningDis = 0;
rightDis[i] = runningDis;
} else{
if(runningDis != Integer.MAX_VALUE) {
runningDis++;
rightDis[i] = runningDis;
}
}
}
runningDis = Integer.MAX_VALUE;
// right to left direction
for(int i=len-1;i>=0;i--){
if(s.charAt(i) == c){
runningDis = 0;
leftDis[i] = runningDis;
} else{
if(runningDis != Integer.MAX_VALUE) {
runningDis++;
leftDis[i] = runningDis;
}
}
}
int[] ans = new int[len];
for(int i=0;i<len;i++){
ans[i] = Math.min(rightDis[i], leftDis[i]);
}
return ans;
}
}