티스토리 뷰

반응형

■ 문제

원본 사이트: https://www.hackerrank.com/challenges/ctci-making-anagrams/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=strings 

 

Strings: Making Anagrams | HackerRank

How many characters should one delete to make two given strings anagrams of each other?

www.hackerrank.com

 

난이도: Easy

최대 스코어: 25

 

● 문제 요약

  • 첫 번째 문자열의 문자를 재배열하여 두 번째 문자열을 형성할 수 있는 경우 두 문자열은 서로의 애너그램이라고 함
  • 첫 번째 문자열: a, 두 번째 문자열: b
  • a와 b의 길이는 다를 수도 있음
  • a와 b가 서로 애너그램이 되기 위해 a, b에서 제거해야하는 문자의 최소 숫자를 return

 

예시:

a = 'cde'
b = 'dcf'
  • a에서 'e'를 제거  -->  a = 'cd'
  • b에서 'f'를 제거  -->  b = 'dc'

==> return 2

 

 

■ 문제 풀이

이 문제는 각 알파벳 문자가 나온 숫자를 카운트해서 비교해 해결했다.
a와 b의 문자열은 모두 [a-z]의 문자로만 이루어져있기 때문에, [a-z] 문자가 나온 횟수를 저장할 counter 배열을 생성하고 모두 0으로 초기화 시켜준다. ([a-z]는 총 26개의 문자이기 때문에 counter의 length도 26!)
그런 다음, 문자열 a에서 각 문자가 나온 횟수를 counter 배열에 추가한다.
같은 방법으로 문자열 b에서 각 문자가 나온 횟수를 counter 배열에 추가하는데, 이 때 문자열 a와의 비교를 위해 해당 문자의 카운터 값을 마이너스 시켜준다.

그러고 나면 counter 배열에 남은 값들은 a에만 있거나, b에만 있는 문자들의 개수가 된다.
이 문자들을 모두 삭제하면 a와 b는 서로 애너그램이 되는 것이다.

이제 counter 배열에 있는 값들을 모두 더해주면 제거해야하는 최소 문자 수가 되는데, 문자열 b에 나온 문자들은 카운터 값을 마이너스(-) 해줬기 때문에 counter[]의 절대값을 더해주면 된다.

 

● 완성 코드 - 25 Points (Max)

'use strict';

const fs = require('fs');

process.stdin.resume();
process.stdin.setEncoding('utf-8');

let inputString = '';
let currentLine = 0;

process.stdin.on('data', function(inputStdin) {
    inputString += inputStdin;
});

process.stdin.on('end', function() {
    inputString = inputString.split('\n');

    main();
});

function readLine() {
    return inputString[currentLine++];
}

/*
 * Complete the 'makeAnagram' function below.
 *
 * The function is expected to return an INTEGER.
 * The function accepts following parameters:
 *  1. STRING a
 *  2. STRING b
 */

function makeAnagram(a, b) {
    // Write your code here
    let counter = [];
    for(let i=0; i<26; i++){
        counter[i] = 0;
    }
    
    for(let i=0; i<a.length; i++){
        counter[a.charCodeAt(i)-97]++;
    }
    for(let i=0; i<b.length; i++){
        counter[b.charCodeAt(i)-97]--;
    }
    
    return counter.reduce((acc, cur, idx) => {
        if(counter[idx] != 0){
            acc += Math.abs(counter[idx]);
        }
        return acc;
    }, 0)
}

function main() {
    const ws = fs.createWriteStream(process.env.OUTPUT_PATH);

    const a = readLine();

    const b = readLine();

    const res = makeAnagram(a, b);

    ws.write(res + '\n');

    ws.end();
}

 

■ 결론

각 문자가 나온 횟수를 카운트해서 비교하는 것이 핵심인 것 같다!

반응형
댓글
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/04   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30
글 보관함