연습장/HackerRank 문제풀이

[HackerRank - Easy] Two Characters - JavaScript

Tesseractjh 2023. 1. 3. 03:41

🔗 문제 링크

https://www.hackerrank.com/challenges/two-characters/problem?isFullScreen=true 

 

Two Characters | HackerRank

Print the length of the longest possible string $t$ you can form.

www.hackerrank.com

✏️ 풀이

function alternate(s) {
    const isAlternate = (str) => [...str].every((v, i) => i % 2 ? v === str[1] : v === str[0]);
    
    const chars = [...new Set(s)];
    let maxLength = 0;
    for (let i = 0; i < chars.length - 1; i++) {
        for (let j = i + 1; j < chars.length; j++) {
            const removed = s.replace(new RegExp(`[^${chars[i]}${chars[j]}]`, 'g'), '');
            if (isAlternate(removed)) {
                maxLength = Math.max(maxLength, removed.length);
            }
        }
    }
    
    return maxLength;
}

먼저 주어진 문자열에 사용된 모든 문자를 구한다. 그 다음 반복문으로 이 중 두 개를 고르는 모든 경우를 확인한다. 이 때 두 문자를 제외한 나머지 문자들을 제거하고 남은 문자열이 alternate(두 문자열이 번갈아 나타남)하다면 maxLength를 갱신하도록 하였다.