Skip to content

Commit 0c2845d

Browse files
authored
Create 821. Shortest Distance to a Character
1 parent c099d43 commit 0c2845d

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

821. Shortest Distance to a Character

+34
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/*
2+
// Given a string S and a character C,
3+
// return an array of integers representing the shortest distance from the character C in the string.
4+
5+
// Example 1:
6+
Input: S = "loveleetcode", C = 'e'
7+
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]
8+
*/
9+
10+
class Solution {
11+
public int[] shortestToChar(String S, char C) {
12+
int len = S.length();
13+
int[] result = new int[len];
14+
int position;
15+
16+
position = Integer.MIN_VALUE / 2;
17+
for (int i = 0; i < len; i++) {
18+
if (S.charAt(i) == C) {
19+
position = i;
20+
}
21+
result[i] = i - position;
22+
}
23+
24+
position = Integer.MAX_VALUE / 2;
25+
for (int i = len-1; i >= 0; i--) {
26+
if (S.charAt(i) == C) {
27+
position = i;
28+
}
29+
result[i] = Math.min(result[i], position - i);
30+
}
31+
32+
return result;
33+
}
34+
}

0 commit comments

Comments
 (0)