-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathL821.java
More file actions
51 lines (49 loc) · 2.17 KB
/
L821.java
File metadata and controls
51 lines (49 loc) · 2.17 KB
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
class Solution821 {
class Solution {
/**
* 821. Shortest Distance to a Character https://leetcode.com/problems/shortest-distance-to-a-character/description/
*
* @param S String
* String to be searched in.
* @param C char
* Character to find minimum distance to
* @return int[] containing distances
* @timeComplexity O(n) where n is the length of string
* @spaceComplexity O(1)
*/
public int[] shortestToChar(String S, char C) {
char[] chars = S.toCharArray();
int[] result = new int[S.length()];
// We maintain three pointers and linearly scan the string
int prevPtr1 = -1; // Previous occurence of C
int ptr1 = -1; // Current occurence of C
int ptr2 = 0; // Scan and reach till ptr1 updating the result array
while (ptr1 < S.length() - 1 && ptr2 < S.length()) {
// Check whether ptr1 has already hit the end of String
if (ptr1 > S.length() - 1) {
while (ptr2 < S.length()) {
result[ptr2] = ptr2 - prevPtr1;
}
return result;
}
// Update prevPointer before finding the next C, but only after first C was found
if (ptr1 >= 0) {
prevPtr1 = ptr1;
}
// Move the ptr1 to nearest C
do {
ptr1++;
} while (ptr1 < S.length() && chars[ptr1] != C);
// Move ptr2 and keep updating result
while (ptr2 < ptr1 && ptr2 < S.length()) {
// If prevPtr isn't yet set, the distance is difference from ptr1
// If ptr1 is outside the string, distance is difference from prevPtr1
// Else the distance is min of those two
result[ptr2] = prevPtr1 < 0 ? (ptr1 - ptr2) : ptr1 >= S.length() ? ptr2 - prevPtr1 : Math.min(ptr1 - ptr2, ptr2 - prevPtr1);
ptr2++;
}
}
return result;
}
}
}