[leetcode] problem 821 – shortest distance to a character

Given a string S and a character C, return an array of integers representing the shortest distance from the character C in the string.

Example

Input: S = “loveleetcode”, C = ‘e’
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

Note

  1. S string length is in [1, 10000].
  2. C is a single character, and guaranteed to be in string S.
  3. All letters in S and C are lowercase.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public int[] shortestToChar(String S, char C) {
int n = S.length();
int[] result = new int[n];
Arrays.fill(result, n);

for (int i = 0; i < n; i++) {
if (S.charAt(i) == C)
result[i] = 0;
else if (i > 0)
result[i] = result[i - 1] + 1;
}

for (int i = n - 2; i >= 0; i--)
result[i] = Math.min(result[i], result[i + 1] + 1);

return result;
}