알고리즘/백준

백준 10808번 - 알파벳 개수 / Go

Hwisaek 2022. 4. 30. 01:40
반응형

문제: https://www.acmicpc.net/problem/10808

 

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
​

출처

  • 문제를 만든 사람: baekjoon
  • 잘못된 데이터를 찾은 사람: djm03178
  • 문제의 오타를 찾은 사람: eric00513

알고리즘 분류


 


정답

package main

import (
	"bufio"
	"fmt"
	"os"
	"strings"
	"testing"
)

func main() {
	rd := bufio.NewReader(os.Stdin)
	wr := bufio.NewWriter(os.Stdout)

	word := scan10808(rd)

	_, _ = wr.WriteString(solution10808(word))
	_ = wr.Flush()
}

func solution10808(word string) (result string) {
	count := make([]int, 26)
	for _, c := range word {
		char := rune(c) - rune('a')
		count[char]++
	}

	for _, i := range count {
		result += fmt.Sprintf("%d ", i)
	}
	result = strings.TrimSpace(result)
	return
}

func scan10808(rd *bufio.Reader) string {
	str, _ := rd.ReadString('\n') // 여기서 text는 마지막에 줄바꿈 문자를 포함하므로
	str = strings.TrimSpace(str)  // 줄바꿈 문자를 제거해야 함
	return str
}

func Benchmark10808(b *testing.B) {
	for i := 0; i < b.N; i++ {
		solution10808("onetwothreefourfivesixseveneightninetenonetwothreefourfivesixseveneightninetenonetwothreefourfivesix")
	}
}

func Test_solution10808(t *testing.T) {
	type args struct {
		word string
	}
	tests := []struct {
		name       string
		args       args
		wantResult string
	}{
		{name: "", args: args{word: "baekjoon"}, wantResult: "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"},
	}
	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if gotResult := solution10808(tt.args.word); gotResult != tt.wantResult {
				t.Errorf("solution10808() = %v, want %v", gotResult, tt.wantResult)
			}
		})
	}
}

 


풀이

 프로그래머스에서 있는 단어의 알파벳 별 개수를 출력하는 문제이다. 이런 류의 글자 확인 문제는 26개로 정해져 있는 알파벳 개수 확인용 배열을 만들어 ascii 코드로 변환하여 'a'를 뺀 다음 해당 인덱스를 더해주면 된다.

반응형