https://school.programmers.co.kr/learn/courses/30/lessons/64064
코드
function solution(user_id, banned_id) {
let answer = new Set();
const get_pattern = (id) => {
const transformed = id.replace(/\*/g, ".");
return new RegExp(`^${transformed}$`);
};
const check_banned = (pattern) => {
return user_id.filter((id) => pattern.test(id));
};
const bt = (idx, banned_set) => {
if (idx === banned_id.length) {
answer.add([...banned_set].sort().join("/"));
return;
}
for (const id of candidates[idx]) {
if (!banned_set.has(id)) {
banned_set.add(id);
bt(idx + 1, banned_set);
banned_set.delete(id);
}
}
};
const candidates = [];
for (const banned of banned_id) {
const p = get_pattern(banned);
candidates.push(check_banned(p));
}
bt(0, new Set());
return answer.size;
}
console.log(
solution(["frodo", "fradi", "crodo", "abc123", "frodoc"], ["fr*d*", "abc1**"])
);
//2
console.log(
solution(
["frodo", "fradi", "crodo", "abc123", "frodoc"],
["*rodo", "*rodo", "******"]
)
);
//2
console.log(
solution(
["frodo", "fradi", "crodo", "abc123", "frodoc"],
["fr*d*", "*rodo", "******", "******"]
)
);
//3
get_pattern(): 불량 사용자 아이디를 정규표현식으로 바꾼다. 이때, "*"은 정규표현식에서 단일 문자를 의미하는 "."으로 바꾼다.
check_banned(): 사용자 아이디들(user_id) 중 인자로 주어진 정규표현식(pattern)과 일치하는 아이디들의 배열을 리턴한다.
bt(): 백트래킹을 이용하여 가능한 아이디 조합을 구한다. 이때 가능한 아이디 조합 내에서 중복을 거르기 위해 집합을 사용하고, 또 가능한 아이디 조합들에서도 중복을 거르기 위해 집합을 사용한다.
'문제풀이 > 백트래킹' 카테고리의 다른 글
[Python/파이썬] 백준 22953번 도도의 음식 준비 (3) | 2025.06.02 |
---|---|
[Javascript/자바스크립트] (프로그래머스) 양과 늑대 (0) | 2025.05.09 |
[Python/파이썬] 백준 14650번 걷다보니 신천역 삼 (Small) (0) | 2025.04.26 |
[Python/파이썬] 백준 2057번 팩토리얼 분해 (0) | 2025.04.07 |
[Python/파이썬] 백준 25369번 카드 숫자 곱을 최소로 만들기 (0) | 2025.04.02 |