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

[Baekjoon] 10820 문자열 분석(파이썬/자바스크립트/NodeJS)

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

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

 

10820번: 문자열 분석

문자열 N개가 주어진다. 이때, 문자열에 포함되어 있는 소문자, 대문자, 숫자, 공백의 개수를 구하는 프로그램을 작성하시오. 각 문자열은 알파벳 소문자, 대문자, 숫자, 공백으로만 이루어져 있

www.acmicpc.net


문제

문자열 N개가 주어진다. 이때, 문자열에 포함되어 있는 소문자, 대문자, 숫자, 공백의 개수를 구하는 프로그램을 작성하시오.

각 문자열은 알파벳 소문자, 대문자, 숫자, 공백으로만 이루어져 있다.

입력

첫째 줄부터 N번째 줄까지 문자열이 주어진다. (1 ≤ N ≤ 100) 문자열의 길이는 100을 넘지 않는다.

 

출력

첫째 줄부터 N번째 줄까지 각각의 문자열에 대해서 소문자, 대문자, 숫자, 공백의 개수를 공백으로 구분해 출력한다.

예제 입력 1

This is String
SPACE    1    SPACE
 S a M p L e I n P u T     
0L1A2S3T4L5I6N7E8

예제 출력 1

10 2 0 2
0 10 1 8
5 6 0 16
0 8 9 0

정답 코드

나의 코드
파이썬 Ver.
import sys


def mySolution():
    while True:
        low, up, num, space = 0, 0, 0, 0
        data = sys.stdin.readline().rstrip("\n")

        if not data:
            break

        for c in data:
            if c.islower():
                low += 1
            elif c.isupper():
                up += 1
            elif c.isdigit():
                num += 1
            elif c.isspace():
                space += 1

        print(low, up, num, space)


mySolution()


자바스크립트/NodeJS Ver.

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

const solution1 = (data) => {
    for (let i of data) {
        if (!i) continue;
        let [low, up, num, space] = [0, 0, 0, 0];
        for (let j of i) {
            if (j >= 'a' && j <= 'z') low++;
            else if (j >= 'A' && j <= 'Z') up++;
            else if (j >= '0' && j <= '9') num++;
            else if (j === ' ') space++;
        }

        console.log(low, up, num, space);
    }
};

console.log('solution1');
solution1(input);
답안 2
const fs = require('fs');
const filePath = process.platform === 'linux' ? '/dev/stdin' : './input.txt';
let input = fs.readFileSync(filePath).toString().split('\n');

const solution2 = (data) => {
    const t = input.filter((str) => str.length < 1);

    if (t.length) {
        input.splice(input.indexOf(t[0]), 1);
    }

    input.forEach((str) => {
        const lower = str.length - str.replace(/[a-z]/g, '').length;
        const upper = str.length - str.replace(/[A-Z]/g, '').length;
        const num = str.length - str.replace(/[0-9]/g, '').length;
        const blank = str.length - str.replace(/\ /g, '').length;

        console.log(lower, upper, num, blank);
    });
};

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

문제 풀이

 이번 문제는 입력값을 받는 과정이 다소 까다롭다. 보통 입력값의 개수가 주어지는데 이 문제에는 주어지지 않아서 별도 로직으로 처리해야 한다. 따라서 while 반복문을 돌면서 입력값이 있다면 로직을 실행하고 없다면 break로 반복문을 빠져나오도록 코드를 짜야 한다.

 정답 도출을 위한 로직은 간단하다. is ~ 메서드를 활용하여 탐색하는 문자가 해당 조건에 맞는지 확인하고 조건에 맞는 변수의 값을 1씩 증가시키면 되는 문제이다.


함께 보기

https://gdk01.tistory.com/217

 

[Baekjoon] 10808 알파벳 개수(파이썬 python)

이번 문제는 아래 링크에서 풀어볼 수 있습니다. 10808번: 알파벳 개수 단어에 포함되어 있는 a의 개수, b의 개수, …, z의 개수를 공백으로 구분해서 출력한다. www.acmicpc.net 문제 알파벳 소문자로만

gdk01.tistory.com

https://imkh.dev/algorithm-boj-10820/

 

(Node.js) 백준 10820번 문자열 분석 문제 | imkh.dev

백준 10820번 문자열 분석 문제 솔루션

imkh.dev

 

728x90
반응형

댓글