[LeetCode] Shortest Distance to a Character

아르당·2026년 2월 28일

LeetCode

목록 보기
176/213
post-thumbnail

문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음

Problem

문자열 s와 s에 나타나는 문자 c가 주어졌을 때, answer.length == s.length이고 answer[i]가 인덱스 i에서 s에서 문자 c가 가장 가까이 나타나는 위치까지의 거리인 정수 배열 answer를 반환해라.

두 인덱스 i와 j 사이의 거리는 abs(i - j)이며, 여기서 abs는 절대값 함수이다.

Example

#1
Input: s = "loveleetcode", c = "e"
Output: [3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0]

#2
Input: s = "aaab", c = "b"
Output: [3, 2, 1, 0]

Constraints

  • 1 <= s.length <= 10^4
  • s[i]와 c는 영어 소문자이다.
  • c는 s에서 적어도 한 번은 발생한다는 것을 보장한다.

Solved

class Solution {
    public int[] shortestToChar(String s, char c) {
        int n = s.length();
        int[] result = new int[n];

        for(int i = 0; i < n; ++i){
            result[i] = s.charAt(i) == c ? 0 :n;
        }

        for(int i = 1; i < n; ++i){
            result[i] = Math.min(result[i], result[i - 1] + 1);
        }

        for(int i = n - 2; i >= 0; --i){
            result[i] = Math.min(result[i], result[i + 1] + 1);
        }

        return result;
    }
}
profile
내 마음대로 코드 작성하는 세상

0개의 댓글