가장 많은 글자

문제

언어

  • JavaScript

순서도

  1. 문자열에서 알파벳 별로 개수 세기
  2. 가장 많은 알파벳만 따로 모으기

문제 풀이 step 1

  • 어떤 글이 주어졌을 때, 가장 많이 나온 글자를 출력하는 문제입니다.
  • 전체 문자열을 순회하며, 각 알파벳의 개수를 세어줍니다.
  • 그리고 가장 개수가 많은 알파벳을 모아서 출력하면 정답입니다.
  • 추가 설명은 주석으로 작성하겠습니다.

소스 코드

const input = require("fs")
	.readFileSync("/dev/stdin")
	.toString()
	.trim()
	.split("\n");

const solution = (input) => {
	const alphabets = "abcdefghijklmnopqrstuvwxyz";
	const str = input.join("");

	const arr = Array(26).fill(0);
	let max = 0;

	// 문자열에서 각 알파벳의 개수 세기
	for (let i = 0; i < str.length; i++) {
		const chNum = str[i].charCodeAt(0) - "a".charCodeAt(0);

		if (chNum < 0) continue;

		arr[chNum] += 1;
		max = Math.max(max, arr[chNum]);
	}

	// 가장 개수가 많은 알파벳 모으기
	let ans = "";
	for (let i = 0; i < 26; i++) {
		if (arr[i] === max) ans += alphabets[i];
	}

	return ans;
};

console.log(solution(input));