본문 바로가기
Problem Solving/LeetCode

[LeetCode] 821. Shortest Distance to a Character - Java

by graycode 2026. 10. 20.

• 문제 링크

 

Shortest Distance to a Character - LeetCode

Can you solve this real interview question? Shortest Distance to a Character - Given a string s and a character c that occurs in s, return an array of integers answer where answer.length == s.length and answer[i] is the distance from index i to the closest

leetcode.com

 

• 풀이 코드

public class Solution {

    public int[] shortestToChar(String s, char c) {
        int[] arr = new int[s.length()];
        int n = -arr.length;
        for (int i = 0; i < arr.length; i++) {
            if (s.charAt(i) == c) n = i;
            arr[i] = i - n;
        }

        n = 2 * arr.length;
        for (int i = arr.length - 1; i >= 0; i--) {
            if (s.charAt(i) == c) n = i;
            arr[i] = Math.min(arr[i], n - i);
        }

        return arr;
    }

}

댓글