TGViewer
Java | LeetCode Java | LeetCode @easy_java_task · 6.44K subscribers
Post #1963 557
Задача: 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⃣Мы берем минимальное значение из этих двух ответов для создания нашего окончательного ответа.

😎 Решение:
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.charAt(i) == C) {
prev = i;
}
ans[i] = i - prev;
}

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

return ans;
}


Ставь 👍 и забирай 📚 Базу знаний
More from @easy_java_task
  1. Oct 12, 2026Post #2292
  2. Oct 11, 2026Задача: 672. Bulb Switcher II Сложность: medium Есть комната с n лампочками, пронумерованн…
  3. Oct 10, 2026Post #2290
  4. Oct 10, 2026Задача: 723. Candy Crush Сложность: medium Этот вопрос касается реализации базового алгори…
  5. Oct 9, 2026Задача: 1266. Minimum Time Visiting All Points Сложность: easy На двумерной плоскости имее…
  6. Oct 7, 2026Задача: 350. Intersection of Two Arrays II Сложность: easy Даны два целочисленных массива…
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 →