|
2 | 2 |
|
3 | 3 | import java.util.TreeSet;
|
4 | 4 |
|
5 |
| -/** |
6 |
| - * 821. Shortest Distance to a Character |
7 |
| -
|
8 |
| - Given a string S and a character C, |
9 |
| - return an array of integers representing the shortest distance from the character C in the string. |
10 |
| -
|
11 |
| - Example 1: |
12 |
| -
|
13 |
| - Input: S = "loveleetcode", C = 'e' |
14 |
| - Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0] |
15 |
| -
|
16 |
| - Note: |
17 |
| -
|
18 |
| - S string length is in [1, 10000]. |
19 |
| - C is a single character, and guaranteed to be in string S. |
20 |
| - All letters in S and C are lowercase. |
21 |
| -
|
22 |
| - */ |
23 | 5 | public class _821 {
|
24 | 6 |
|
25 |
| - public static class Solution1 { |
26 |
| - public int[] shortestToChar(String S, char C) { |
27 |
| - int[] result = new int[S.length()]; |
28 |
| - TreeSet<Integer> cIndices = new TreeSet(); |
29 |
| - for (int i = 0; i < S.length(); i++) { |
30 |
| - if (S.charAt(i) == C) { |
31 |
| - cIndices.add(i); |
32 |
| - } |
33 |
| - } |
34 |
| - for (int i = 0; i < S.length(); i++) { |
35 |
| - int leftDist = Integer.MAX_VALUE; |
36 |
| - if (cIndices.floor(i) != null) { |
37 |
| - leftDist = Math.abs(cIndices.floor(i) - i); |
38 |
| - } |
39 |
| - int rightDist = Integer.MAX_VALUE; |
40 |
| - if (cIndices.ceiling(i) != null) { |
41 |
| - rightDist = Math.abs(cIndices.ceiling(i) - i); |
| 7 | + public static class Solution1 { |
| 8 | + public int[] shortestToChar(String S, char C) { |
| 9 | + int[] result = new int[S.length()]; |
| 10 | + TreeSet<Integer> cIndices = new TreeSet(); |
| 11 | + for (int i = 0; i < S.length(); i++) { |
| 12 | + if (S.charAt(i) == C) { |
| 13 | + cIndices.add(i); |
| 14 | + } |
| 15 | + } |
| 16 | + for (int i = 0; i < S.length(); i++) { |
| 17 | + int leftDist = Integer.MAX_VALUE; |
| 18 | + if (cIndices.floor(i) != null) { |
| 19 | + leftDist = Math.abs(cIndices.floor(i) - i); |
| 20 | + } |
| 21 | + int rightDist = Integer.MAX_VALUE; |
| 22 | + if (cIndices.ceiling(i) != null) { |
| 23 | + rightDist = Math.abs(cIndices.ceiling(i) - i); |
| 24 | + } |
| 25 | + result[i] = Math.min(leftDist, rightDist); |
| 26 | + } |
| 27 | + return result; |
42 | 28 | }
|
43 |
| - result[i] = Math.min(leftDist, rightDist); |
44 |
| - } |
45 |
| - return result; |
46 | 29 | }
|
47 |
| - } |
48 | 30 | }
|
0 commit comments