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

김개발·2021년 7월 23일
0

프로그래머스

목록 보기
24/42

문제 푼 날짜 : 2021-07-21

문제

문제 링크 : https://programmers.co.kr/learn/courses/30/lessons/81301

접근 및 풀이

카카오 코딩테스트에 자주 등장하는 문자열 처리 문제였다.
영단어(key)에 대응하는 숫자(value)를 map에 저장하였고, 숫자가 나오기 전까지 문자열을 체크해주다가 map에 저장된 영단어가 완성되면 영단어에 매칭되는 value를 결과값에 추가해주었다.

코드

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

using namespace std;

int solution(string s) {
    map<string, int> m;
    m["zero"] = 0;
    m["one"] = 1;
    m["two"] = 2;
    m["three"] = 3;
    m["four"] = 4;
    m["five"] = 5;
    m["six"] = 6;
    m["seven"] = 7;
    m["eight"] = 8;
    m["nine"] = 9;
    
    string ans = "";
    string str = "";
    for (auto c : s) {
        if (isdigit(c) == false) {
            str += c;
            if (m.find(str) != m.end()) {
                ans += to_string(m[str]);
                str = "";
            }
        } else {
            ans += c;
        }
    }
    
    int answer = stoi(ans);
    return answer;
}

결과

피드백

C++로 문제를 풀기 때문에 문자열 처리를 위해 자주 이용되는 다양한 기능들을 익혀둬야겠다.

profile
개발을 잘하고 싶은 사람

0개의 댓글