-
Notifications
You must be signed in to change notification settings - Fork 41
/
solution.js
50 lines (46 loc) · 1.08 KB
/
solution.js
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
/**
* @param {string} S
* @param {character} C
* @return {number[]}
*/
var shortestToChar = function (S, C) {
const result = new Array(S.length);
const indexs = [];
// 记录所有为C的位置
for (let i = 0; i < S.length; i++) {
if (S[i] === C) {
indexs.push(i);
result[i] = 0;
}
}
// 在两个C位之间的
for (let i = 0; i < indexs.length - 1; i++) {
let index1 = indexs[i] + 1;
let index2 = indexs[i + 1] - 1;
let count = 1;
while (index1 <= index2) {
result[index1] = count;
result[index2] = count;
count++;
index1++;
index2--;
}
}
// 最左侧元素
let count = 1;
let index1 = indexs[0] - 1;
while (index1 > -1) {
result[index1] = count;
index1--;
count++;
}
// 最右侧元素
count = 1;
index1 = indexs[indexs.length - 1] + 1;
while (index1 < S.length) {
result[index1] = count;
index1++;
count++;
}
return result;
};