-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSolution821.cs
41 lines (34 loc) · 892 Bytes
/
Solution821.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
using System.Text;
using LeetCode.DataStructures;
namespace LeetCode.Solutions;
public class Solution821
{
/// <summary>
/// 821. Shortest Distance to a Character - Easy
/// <a href="https://leetcode.com/problems/shortest-distance-to-a-character">See the problem</a>
/// </summary>
public int[] ShortestToChar(string s, char c)
{
var n = s.Length;
var result = new int[n];
var prev = int.MinValue / 2;
for (var i = 0; i < n; i++)
{
if (s[i] == c)
{
prev = i;
}
result[i] = i - prev;
}
prev = int.MaxValue / 2;
for (var i = n - 1; i >= 0; i--)
{
if (s[i] == c)
{
prev = i;
}
result[i] = Math.Min(result[i], prev - i);
}
return result;
}
}