본문 바로가기
코딩 테스트/프로그래머스(lv1)

[프로그래머스]숫자 문자열과 영단어(c++)

by 계양구놈팽이 2022. 5. 16.

https://programmers.co.kr/learn/courses/30/lessons/81301

 

코딩테스트 연습 - 숫자 문자열과 영단어

네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다. 다음은 숫자의 일부 자

programmers.co.kr

 

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

unordered_map<string, int> number_map =
{   {"zero",0 },
    {"one", 1 },
    {"two", 2 },
    {"three", 3 },
    {"four", 4 },
    {"five", 5 },
    {"six", 6 },
    {"seven", 7 },
    {"eight", 8 },
    {"nine", 9 },
};


int solution(string s) {
    int answer = 0;

    for (auto& its : number_map)
    {
        auto key = its.first;

        while (s.find(key) != s.npos)
        {
            s.replace(s.find(key), key.size(), to_string(its.second));
        }
    }

    return stoi(s);
}

int main()
{
    string s = "one4oneseveneight";
    cout << solution(s);
}

 

std::string은 문자열을 저장할 수 있는 컨테이너이다. stl에서 제공하는 vector와 매우 유사한 감각으로 사용할 수 있다. 게다가, 문자열을 저장하는 컨테이너 답게,  문자열 조작에 특화된 함수를 가지고 있다. 이 문제에서는 find와 replace 두가지를 사용해 보았다.

 

  • find : string에서 특정 문자 탐색, 문자의 시작 점을 반환
  • replace :  string에서 일정 부분을 변경가능