• 문제 링크
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;
}
}'Problem Solving > LeetCode' 카테고리의 다른 글
| [LeetCode] 830. Positions of Large Groups - Java (0) | 2026.10.23 |
|---|---|
| [LeetCode] 824. Goat Latin - Java (0) | 2026.10.21 |
| [LeetCode] 819. Most Common Word - Java (0) | 2026.10.19 |
| [LeetCode] 812. Largest Triangle Area - Java (0) | 2026.10.18 |
| [LeetCode] 806. Number of Lines To Write String - Java (0) | 2026.10.17 |
댓글