TGViewer
C# | LeetCode C# | LeetCode @easy_c_sharp_task · 3.18K subscribers
Post #1641 284
Задача: 821. Shortest Distance to a Character
Сложность: easy

Дана строка s и символ c, который встречается в s. Верните массив целых чисел answer, где answer.length == s.length, и answer[i] - это расстояние от индекса i до ближайшего появления символа c в строке s.

Расстояние между двумя индексами i и j равно abs(i - j), где abs - это функция абсолютного значения.

Пример:
Input: s = "loveleetcode", c = "e"
Output: [3,2,1,0,1,0,0,1,2,2,1,0]
Explanation: The character 'e' appears at indices 3, 5, 6, and 11 (0-indexed).
The closest occurrence of 'e' for index 0 is at index 3, so the distance is abs(0 - 3) = 3.
The closest occurrence of 'e' for index 1 is at index 3, so the distance is abs(1 - 3) = 2.
For index 4, there is a tie between the 'e' at index 3 and the 'e' at index 5, but the distance is still the same: abs(4 - 3) == abs(4 - 5) = 1.
The closest occurrence of 'e' for index 8 is at index 6, so the distance is abs(8 - 6) = 2.


👨‍💻 Алгоритм:

1⃣При проходе слева направо будем запоминать индекс prev последнего символа C, который мы видели. Тогда ответ будет i - prev.

2⃣При проходе справа налево будем запоминать индекс prev последнего символа C, который мы видели. Тогда ответ будет prev - i.

3⃣Мы берем минимальное значение из этих двух ответов для создания нашего окончательного ответа.

😎 Решение:
public class Solution {
public int[] ShortestToChar(string S, char C) {
int N = S.Length;
int[] ans = new int[N];
int prev = -N;

for (int i = 0; i < N; ++i) {
if (S[i] == C) {
prev = i;
}
ans[i] = i - prev;
}

prev = 2 * N;
for (int i = N - 1; i >= 0; --i) {
if (S[i] == C) {
prev = i;
}
ans[i] = Math.Min(ans[i], prev - i);
}

return ans;
}
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_c_sharp_task
  1. Oct 11, 2026Задача: 1061. Lexicographically Smallest Equivalent String Сложность: medium Даны две стро…
  2. Oct 9, 2026Задача: 525. Contiguous Array Сложность: medium Дан бинарный массив nums. Верните максимал…
  3. Oct 7, 2026Задача: 1509. Minimum Difference Between Largest and Smallest Value in Three Moves Сложнос…
  4. Oct 7, 2026🔥 Скрытые вакансии с удаленной работой для C# разработчика, которые нигде больше не публи…
  5. Oct 6, 2026Задача: 645. Set Mismatch Сложность: easy У вас есть набор целых чисел s, который изначаль…
  6. Oct 5, 2026Задача: 927. Three Equal Parts Сложность: hard Вам дан массив arr, состоящий только из нул…
Threads Profile ViewerView any public Threads profile without an account.Open ThreadLook →Writing with AI? Make it sound human.Metric37 rewrites AI drafts so they read naturally. Free AI detector, 1,500 words free.Try Metric37 →