[알고리즘] 알파벳의 최빈값 찾기

마데슾 : My Dev Space·2021년 6월 16일
0

알고리즘

목록 보기
5/9

계획

  1. 각 알파벳별로 빈도수를 저장할 길이가 26인 배열을 만든다
  2. 입력값을 순회하여 탐색중인 요소에 해당하는 인덱스의 숫자에 + 1을 해준다
  3. 모든 알파벳의 빈도수가 담긴 배열을 순회하여 빈도수가 가장 많은 알파벳을 반환한다

각 알파벳의 인덱스 구하는 방법

아스키 코드를 보면,
a ~ z97 ~ 122로 표현됩니다
이를 이용하여 인덱스를 구할 수 있습니다.

  1. 문자열을 아스키코드로 변환합니다
  2. 변환된 아스키코드에서 97(a 의 아스키코드)을 뺍니다
  3. 2번의 결과값이 해당 알파벳이 저장되어 있는 인덱스입니다
a => 97 => 97 - 97 => 0 => a 인덱스는 0
b => 98 => 98 - 97 => 1 => b 인덱스는 1
c => 99 => 99 - 97 => 2 => b 인덱스는 2

위와같은 방법으로 인덱스를 구하면 됩니다.

반대로 인덱스를 다시 아스키코드로 바꿀땐 97(a 의 아스키코드)을 다시 더해주면 됩니다
인덱스 + 97(a 의 아스키코드)

실행

자바스크립트

function maxOccurenceAlphabet(string) {
  const stringList = string.split('');

  const aASCIICode = 'a'.charCodeAt(0);

  const store = stringList.reduce((acc, cur) => {
    const stringToASCII = cur.charCodeAt(0);

    if (stringToASCII >= 97 && stringToASCII <= 122) {
      const index = stringToASCII - aASCIICode;

      acc[index] += 1;
    }

    return acc;
  }, Array(26).fill(0));

  let maxOccurence = 0;
  let maxAlphabetIndex = 0;

  store.forEach((number, index) => {
    if (maxOccurence < number) {
      maxOccurence = number;
      maxAlphabetIndex = index;
    }
  });

  return String.fromCharCode(maxAlphabetIndex + aASCIICode);
}

파이썬

def find_max_occurred_alphabet(string):
    alphabet_occurrence_array = [0] * 26

    for char in string:
        if not char.isalpha():
            continue
        arr_index = ord(char) - ord('a')
        alphabet_occurrence_array[arr_index] += 1

    max_occurrence = 0
    max_alphabet_index = 0
    for index in range(len(alphabet_occurrence_array)):
        alphabet_occurrence = alphabet_occurrence_array[index]
        if alphabet_occurrence > max_occurrence:
            max_occurrence = alphabet_occurrence
            max_alphabet_index = index
profile
👩🏻‍💻 🚀

0개의 댓글