
문자열과 문자(t)가 주어지면 문자열의 각 문자가 t와 떨어진 최소거리를 출력
function solution(s,t) {
let answer = [];
let num = 1000;
for(let x of s){
if(x===t){
num = 0;
answer.push(num);
}else{
num++;
answer.push(num);
}
}
num = 1000;
for(let i=s.length-1; i>=0; i--){
if(s[i]===t) {
num = 0;
answer.push(num);
}else {
num++;
answer[i]=Math.min(answer[i], num);
}
}
return answer;
}
let str = 'teachermode';
console.log(solution(str,'e'));
첫 번째 for문은 문자열 순서대로 돌면서 문자 t와 떨어진 거리를 구함
두 번째 for문은 문자열을 거꾸로 돌면서 문자 t와 떨어진 거리를 구함
두 개의 for문에서 구한 떨어진 거리를 비교하여 더 작은 값을 반환
Math.min(값1, 값2) : 두 값 중 작은 값을 반환