코딩테스트/프로그래머스
[JavaScript] 프로그래머스 - 단어 변환 (3단계)
배똥회장
2022. 8. 4. 13:44
728x90
코딩 테스트 풀이 체크리스트 |
|
2시간 내에 풀었는가? | O |
본인의 실력으로 풀었는가? | O |
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
function solution(begin, target, words) {
//words에 target이 없으면 0 리턴
if (words.indexOf(target) == -1) return 0;
//bfs?를 위해 만든 큐
let queue = new Array();
//나중에 글자 비교를 위해 target을 문자열 배열로 만들기
target = target.split("");
//words의 문자들도 문자열 배열로 각각 만들어 담기
for (i = 0; i < words.length; i++) {
words[i] = words[i].split("");
}
//큐에 begin 글자와 변형된 횟수인 0을 매개변수로 Word형으로 만들어 담는다
queue.push(new Word(begin.split(""), 0));
//큐가 0이 될 때까지 반복
while (queue.length > 0) {
//큐의 제일 첫번째 항목 가져오기
let word = queue.shift();
//항목의 글자와 변형 횟수 가져오기
let arr = word.w;
let index = word.index;
//만약 글자가 target과 동일하다면 바로 해당 횟수 리턴
if (check(arr, target) == 0) return index;
//words의 문자들을 하나씩 꺼내면서 글자와 비교
for (i = 0; i < words.length; i++) {
let count = words[i].length;
for (j = 0; j < words[i].length; j++) {
if (arr[j] == words[i][j]) count--;
}
//만약 글자 차이가 1개 밖에 없으면 큐에 넣으면서 words에서는 삭제
if (count == 1) {
queue.push(new Word(words[i], index+1));
words.splice(i, 1);
}
}
}
//while문이 끝나면 변형할 수 없는 것이기 때문에 0 리턴
return 0;
}
function check(w1, w2) {
let count = w1.length;
for (i = 0; i < w1.length; i++) {
if (w1[i] == w2[i]) count--;
}
return count;
}
class Word {
constructor(word, i) {
this.w = word;
this.index = i;
}
}
테스트 1 〉 | 통과 (0.33ms, 30.1MB) |
테스트 2 〉 | 통과 (0.40ms, 30.2MB) |
테스트 3 〉 | 통과 (0.57ms, 30MB) |
테스트 4 〉 | 통과 (0.20ms, 30.3MB) |
테스트 5 〉 | 통과 (0.10ms, 30.1MB) |
728x90