풀이
김영준
function solution(s) { const result = [-1]; // 처음에는 무조건 -1 for(let i = 1; i < s.length; i++){ let front = 0; // 거리 변수 for(let j = i - 1; j >= 0; j--) { // 현재 문자의 이전 문자부터 첫 번째 문자까지 반복 front++; if(s[i] === s[j]){ // 같으면 현재 거리를 push result.push(front); break; } if( j === 0 ) result.push(-1); // 같은게 없으면 -1 push } } return result; } // 예비군 다녀오겠습니다. 파이팅!
이종현
function solution(s) { const answer = []; const arr = []; for (let i = 0; i < s.length; i++) { if (!arr.includes(s[i])) { arr.push(s[i]); answer.push(-1); } else { let idx = arr.lastIndexOf(s[i]); arr.push(s[i]); answer.push(i - idx); } } return answer; }
박노철
function solution(s) { /* s의 각 위치마다 자신보다 앞에 나왔으면서 자신과 가장 가까운 곳에 있는 같은 글자 */ s=s.split(""); //처음 나왔다면 -1, const answer=[]; for(let i =0; i<s.length ; i++){ //indexof와 i 를 비교해서 같다면 -1, 다르다면 그차이를 넣어준 후 중복방지 처리를 위해 0을 넣어준다. let a =s[i]; let idx=s.indexOf(a); // 같다면 앞에는 같은 글자가 없다. if(idx ===i)answer.push(-1); else{ answer.push(i-idx) s[idx]=0; } } return answer }
이민희
function solution(s) { const distances = [] // 각각 몇 칸 앞에 있는지 담을 배열 // 왼쪽부터 오른쪽으로 순차적으로 순회한다. for (let i = 0; i < s.length; i++) { const currentChar = s[i] // 현재 순회 중인 문자 let isFirstChar = true; // 처음 나온 문자인지 확인하는 플래그 // i 이전 인덱스부터 첫 번째 인덱스 0까지 거꾸로 순회한다. for (let j = i - 1; j >= 0; j--) { const targetChar = s[j] // 현재 순회 중인 문자 // 같은 문자가 나타나면, i와 j의 차이를 distances 배열에 삽입한다. if (currentChar === targetChar) { distances.push(i - j) isFirstChar = false; break; } } if (isFirstChar) distances.push(-1) } return distances }
박건우
function solution(s) { const answer = []; const memory = {}; [...s].forEach((letter, index) => { memory[letter] >= 0 ? answer.push(index - memory[letter]) // memory에 letter가 있다면 거리 계산 후 푸시 : answer.push(-1); // 그렇지 않다면 -1 푸시 memory[letter] = index; // 메모리에 거리 저장 }) return answer; }
박주연
function solution(s) { const answer = []; for(let i =0; i<s.length;i++){ const str = s.slice(0,i); answer.push(str.lastIndexOf(s[i]) === -1 ? -1 : i - str.lastIndexOf(s[i])) } return answer; }