문제를 이해하고 있다면 바로 풀이를 보면 됨
전체 코드로 바로 넘어가도 됨
마음대로 번역해서 오역이 있을 수 있음
문자열 s와 s에 나타나는 문자 c가 주어졌을 때, answer.length == s.length이고 answer[i]가 인덱스 i에서 s에서 문자 c가 가장 가까이 나타나는 위치까지의 거리인 정수 배열 answer를 반환해라.
두 인덱스 i와 j 사이의 거리는 abs(i - j)이며, 여기서 abs는 절대값 함수이다.
#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]
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;
}
}