-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path0821-ShortestDistanceToACharacter.cs
45 lines (41 loc) · 1.2 KB
/
0821-ShortestDistanceToACharacter.cs
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
//-----------------------------------------------------------------------------
// Runtime: 224ms
// Memory Usage: 30.9 MB
// Link: https://leetcode.com/submissions/detail/331974846/
//-----------------------------------------------------------------------------
namespace LeetCode
{
public class _0821_ShortestDistanceToACharacter
{
public int[] ShortestToChar(string S, char C)
{
var result = new int[S.Length];
var distance = S.Length;
for (int i = 0; i < S.Length; i++)
{
if (S[i] == C)
{
result[i] = 0;
distance = 1;
}
else
{
if (result[i] < distance)
result[i] = distance++;
}
}
distance = S.Length;
for (int i = S.Length - 1; i >= 0; i--)
{
if (S[i] == C)
distance = 1;
else
{
if (result[i] > distance)
result[i] = distance++;
}
}
return result;
}
}
}