[프로그래머스] 모음사전 [cpp]

lsh235·2024년 12월 6일
0

CodingTest

목록 보기
28/31

문제 : https://school.programmers.co.kr/learn/courses/30/lessons/84512?language=cpp

핵심

각 자리에 올 수 있는 수에 대한 가중치 계산 필요
현재 자리에 대한 idx * 가중치 + 1

result += idx * weights[i] + 1;


#include <iostream>
#include <string>
#include <unordered_map>
#include <vector>
using namespace std;

int solution(string word) {
    // 각 자리에서 알파벳이 가져오는 가중치 계산
    // 5^4 + 5^3 + 5^2 + 5^1 + 5^0
    // 5^3 + 5^2 + 5^1 + 5^0
    // 5^2 + 5^1 + 5^0
    // 5^1 + 5^0
    // 5^0
    vector<int> weights = {781, 156, 31, 6, 1}; // 각 자릿수별 가중치
    unordered_map<char, int> alphabet_index = {{'A', 0}, {'E', 1}, {'I', 2}, {'O', 3}, {'U', 4}};

    int result = 0;

    for (int i = 0; i < word.size(); ++i) {
        // 현재 알파벳의 순서 계산
        // 각 알파벳의 위치별 현재 위치에 대한 반복 횟수 더하고
        int idx = alphabet_index[word[i]];
        // 해당 자리에 알파벳이 오기까지 위한 가중치를 곱해서 더함.
        result += idx * weights[i] + 1; // 해당 자리의 가중치 반영
    }

    return result;
}

0개의 댓글