Oops, All Code!/🤯 Oops, My Algorithm!
♡̈ 07. 프로그래머스:: 둘만의 암호
밍동망동
2024. 7. 8. 23:47
먼저, 문제를 한 줄로 정의하자면
s를 index만큼 이동하고 skip 문자열에 포함된 문자는 건너뛰어야한다.
이 문제를 해결하기 위해 다음과 같은 단계를 구성했다.
1. 알파벳 리스트를 구성하고, skip에 포함된 문자를 제거함
2. s 문자열을 순회하며 index만큼 이동하고, 알파벳 리스트에 포함된 문자는 건너뜀
3. 알파벳이 z를 넘어가면 다시 순회함
4. 변환 문자를 모아 문자열을 생성함
function solution(s, skip, index) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
const skipSet = new Set(skip);
const availableChars = [...alphabet].filter(char => !skipSet.has(char));
let resultString = '';
for (let char of s) {
let currentCharIndex = availableChars.indexOf(char);
let newCharIndex = (currentCharIndex + index) % availableChars.length;
resultString += availableChars[newCharIndex];
}
return resultString;
}
역시 더 간결한 코드가 상단에 노출되어있었다.
다른 사람의 코드
function solution(s, skip, index) {
const alphabet = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j",
"k", "l", "m", "n", "o", "p", "q", "r", "s", "t",
"u", "v", "w", "x", "y", "z"].filter(c => !skip.includes(c));
return s.split("").map(c => alphabet[(alphabet.indexOf(c) + index) % alphabet.length]).join("");
}
성능 측면에서 비슷하지만, 더욱 간결하다.
내 코드는 더 가독성이 높지만 문제를 알고있는 상태에서는 이 코드가 더 간결하니 도움이 될 것 같다.