문자열 s가 주어졌을 때, s의 각 위치마다 자신보다 앞에 나왔으면서, 자신과 가장 가까운 곳에 있는 같은 글자가 어디 있는지 알고 싶습니다.
예를 들어, s="banana"라고 할 때, 각 글자들을 왼쪽부터 오른쪽으로 읽어 나가면서 다음과 같이 진행할 수 있습니다.
s | result |
---|---|
"banana" | [-1, -1, -1, 2, 2, 2] |
"foobar" | [-1, -1, 1, -1, -1, -1] |
function solution(s) {
let answer = [];
let a = [];
[...s].forEach((value, idx, arr) => {
a.includes(value) ? answer.push(idx - a.lastIndexOf(value)) : answer.push(-1);
a.push(value);
});
return answer;
}
🤍 lastIndexOf(검색문자열[, 검색을 시작할 위치])
'AXCBCX'.lastIndexOf('X'); // 5
'AXCXCX'.lastIndexOf('X', 3); // 3 ('AXCX' 마지막 X의 index)