링크 : https://school.programmers.co.kr/learn/courses/30/lessons/120956
lv.0 마지막 문제로 정답률이 30% 초반이다.
어려울거라고 생각하고 풀었다.
나의 풀이
내가 했던 풀이는 다소 난잡하지만 아래와 같다.
아마 시간 복잡도가 On2 으로 좋은 풀이 방법은 아니라고 생각한다.
그렇지만 내가 구현할 수 있는 최선의 방법이였다.
순열을 구한다.
순열을 구하는 문제는 이미 파이썬에서 해보았던 거라 크게 어렵진 않았다. 재귀함수를 이용했다.
function getPermutations(arr, number) {
const results = [];
if (number === 1) return arr.map((value) => [value]);
arr.forEach((fixed, index, origin) => {
const rest = [...origin.slice(0, index), ...origin.slice(index + 1)];
const permutations = getPermutations(rest, number - 1);
const attached = permutations.map((permutation) => [fixed, ...permutation]);
results.push(...attached);
});
return results;
}
const word2 = getPermutations(word, 2);
const word3 = getPermutations(word, 3);
const word4 = getPermutations(word, 4);
각 순열을 순회하면서 일치하면 count해준다.
앞서 생성한 순열의 배열과 하나씩 비교해서 모든 경우의 수를 비교해준다.
function solution(babbling) {
let count = 0;
for (let i = 0; i < babbling.length; i++) {
for (let j = 0; j < word.length; j++) {
if (babbling[i] === word[j]) {
count += 1;
}
}
for (let j = 0; j < word2.length; j++) {
if (babbling[i] === word2[j].join("")) {
count += 1;
}
}
for (let j = 0; j < word3.length; j++) {
if (babbling[i] === word3[j].join("")) {
count += 1;
}
}
for (let j = 0; j < word4.length; j++) {
if (babbling[i] === word4[j].join("")) {
count += 1;
}
}
}
return count;
}
다른 사람 풀이
문자열을 비교하는 문제는 방향을 정규식으로 방향을 잡는게 훨씬 쉬운 방법인거 같다.
아직까지 정규식을 생성하는 방법이 다소 어려워 이번 기회에 알아보자.
아래는 우선 풀이 방법이다.
function solution(babbling) {
var answer = 0;
const regex = /^(aya|ye|woo|ma)+$/;
babbling.forEach(word => {
if (regex.test(word)) answer++;
})
return answer;
}
^
: 문자열의 시작을 나타냅니다.(aya|ye|woo|ma)
: 이 그룹은 "aya", "ye", "woo", 또는 "ma" 중 하나와 일치합니다.+
: 바로 앞의 요소(이 경우 그룹)를 한 번 이상 일치시킵니다.