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에서 일정 부분을 변경가능
'코딩 테스트 > 프로그래머스(lv1)' 카테고리의 다른 글
[프로그래머스]키패드 누르기(c++) (0) | 2022.05.16 |
---|---|
[프로그래머스]완주하지 못한 선수(C++) (0) | 2022.05.16 |
[프로그래머스]소수만들기(c++) (0) | 2022.05.16 |
[프로그래머스]평균구하기(c++) (0) | 2022.05.16 |