프로그래밍/알고리즘+코딩테스트

프로그래머스/숫자 문자열과 영단어

sleepyotter. 2022. 3. 14. 21:20

적절한 자료구조를 쓰면 풀 수 있다.

1. 숫자면 아무 거리낌 없이 더한다.

2. 문자라면 완성된 문자인지 확인하고, 완성됐다면 map에서 확인하고 값 꺼내서 저장한다.

answer = answer * 10 + value; 하는 부분이 핵심이라면 핵심?

#include <string>
#include <vector>
#include <map>

using namespace std;

int solution(string s) {
    int answer = 0;
    map<string, int> match;
    match["zero"] = 0;
    match["one"] = 1;
    match["two"] = 2;
    match["three"] = 3;
    match["four"] = 4;
    match["five"] = 5;
    match["six"] = 6;
    match["seven"] = 7;
    match["eight"] = 8;
    match["nine"] = 9;
    
    string num="";
    
    for(int i=0; i<s.size(); ++i)
    {
        //숫자라면 넣고
        if(s[i] >= '0' && s[i] <= '9')
        {
            answer = answer * 10 + (s[i]-'0');
        }
        else
        {
            num.push_back(s[i]);
            auto it = match.find(num);
            if(it != match.end())
            {
                num = "";
                answer = answer * 10 + it->second;
            }
        }
    }
    
    return answer;
}