본문 바로가기
👩‍💻 Programming/Coding Test 문제 풀이

[Baekjoon] 10808 알파벳 개수(파이썬/자바스크립트/NodeJS)

by codingBear 2022. 12. 29.
728x90
반응형

이번 문제는 아래 링크에서 풀어볼 수 있습니다.

 

10808번: 알파벳 개수

단어에 포함되어 있는 a의 개수, b의 개수, …, z의 개수를 공백으로 구분해서 출력한다.

www.acmicpc.net


문제

알파벳 소문자로만 이루어진 단어 S가 주어진다. 각 알파벳이 단어에 몇 개가 포함되어 있는지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 단어 S가 주어진다. 단어의 길이는 100을 넘지 않으며, 알파벳 소문자로만 이루어져 있다.

출력

단어에 포함되어 있는 a의 개수, b의 개수, …, z의 개수를 공백으로 구분해서 출력한다.

예제 입력 1

baekjoon

예제 출력 1

1 1 0 0 1 0 0 0 0 1 1 0 0 1 2 0 0 0 0 0 0 0 0 0 0 0

정답 코드

나의 답안 1
파이썬 Ver.
import sys

data = sys.stdin.readline().rstrip()


def mySolution1(data):
    result = [0] * 26

    for i in range(len(data)):
        result[ord(data[i]) - ord("a")] += 1

    return " ".join(map(str, result))


자바스크립트/NodeJS Ver.

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().trim();

const solution1 = (data) => {
    let result = Array(26).fill(0);

    for (let i of data) result[i.charCodeAt() - 'a'.charCodeAt()]++;

    return result.join(' ');
};

console.log('solution1');
console.log(solution1(input));

 

나의 답안 2
파이썬 Ver.
import string
import sys

data = sys.stdin.readline().rstrip()


def mySolution2(data):
    dic = dict()

    for c in string.ascii_lowercase:
        dic[c] = 0

    for c in data:
        dic[c] += 1

    return " ".join(map(str, dic.values()))


print("mySolution2", mySolution2(data))


자바스크립트/NodeJS Ver.

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().trim();

const solution2 = (data) => {
    let obj = {};
    const ASCII = 97;

    for (let i = ASCII; i < ASCII + 26; i++) obj[String.fromCharCode(i)] = 0;

    for (let i of data) {
        obj[i]++;
    }

    return Object.values(obj).join(' ');
};

console.log('solution2');
console.log(solution2(input));
count 메서드 활용
파이썬 Ver.
import sys

data = sys.stdin.readline().rstrip()


def answer1(data):
    result = [0] * 26

    for i in data:
        result[ord(i) - 97] = data.count(i)

    return " ".join(map(str, result))


print("answer1", answer1(data))


자바스크립트/NodeJS Ver.

const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().trim();

const solution3 = (data) => {
    let result = Array(26).fill(0);

    for (let i of data) {
        result[i.charCodeAt() - 97] = data
            .split('')
            .filter((val) => val === i).length;
    }

    return result.join(' ');
};

console.log('solution3');
console.log(solution3(input));
답안 4
const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().trim();

const solution4 = (data) => {
    let map = new Map();

    for (let i = 97; i <= 122; i++) {
        map.set(i, 0);
    }

    for (let i of data) {
        const ascii = i.charCodeAt();

        if (map.has(ascii)) map.set(ascii, map.get(ascii) + 1);
    }

    return Array.from(map.values()).join(' ');
};

console.log('solution4');
console.log(solution4(input));

문제 풀이

 나의 경우 2가지 풀이법을 활용했다. 우선 첫 번째 풀이는 등장횟수를 담는 리스트를 활용한 풀이다. 0을 a부터 z까지 알파벳 개수만큼 가지는 리스트 result를 선언한다. 그 다음 for 반복문으로 입력 받은 문자열을 순회하며 탐색하는 문자의 등장 횟수를 리스트 result에 기록한다. 이때 리스트에 등장 횟수를 기록할 때 쓰일 인덱스는 ord 메서드로써 구한다. for 반복문을 마치고 나서 join으로 리스트 값을 문자열로 만들어 반환하면 정답이다.

 두 번째 방법은 딕셔너리를 활용한 풀이다. string 모듈은 아스키 코드 알파벳 소문자를 제공하는데 이를 활용해 a부터 z까지 알파벳 소문자를 key로 설정하고 각 key의 초기값은 0으로 설정한다. 그런 다음 입력 받은 문자열을 for 반복문으로 순회하며 해당하는 key의 value를 1씩 증가시키고, 딕셔너리의 값만 join 및 map으로 출력하면 정답이다.

 위와 같은 풀이를 count 메서드를 활용해서도 구현할 수 있다. count 메서드는 문자열에 특정 문자가 몇 번 등장했는지 반환하는 함수인데 이를 통해 리스트 result에 문자의 등장 횟수를 기록할 수 있다.


함께 보기

 

https://zetawiki.com/wiki/%ED%8C%8C%EC%9D%B4%EC%8D%AC_A%EC%97%90%EC%84%9C_Z%EA%B9%8C%EC%A7%80_%EB%A6%AC%EC%8A%A4%ED%8A%B8

 

파이썬 A에서 Z까지 리스트 - 제타위키

다음 문자열 포함...

zetawiki.com

https://serendipity24.tistory.com/78

 

[백준][Python] 10808번: 알파벳 개수

https://www.acmicpc.net/problem/10808 10808번: 알파벳 개수 단어에 포함되어 있는 a의 개수, b의 개수, …, z의 개수를 공백으로 구분해서 출력한다. www.acmicpc.net 문제 알파벳 소문자로만 이루어진 단어 S가

serendipity24.tistory.com

https://blockdmask.tistory.com/410

 

[python] 파이썬 count, len 함수 설명과 에제

안녕하세요. BlockDMask 입니다. 오늘은 파이썬 빌트인 함수들중 문자열에서 쓸 수 있는 함수 2가지를 가지고 왔습니다. 미리 요약을 해보자면 문자열의 길이를 구하는 len 함수, 문자열 내부에서 특

blockdmask.tistory.com

 

728x90
반응형

댓글