숫자 문자열과 영단어

NJW·2022년 3월 28일
0

코테

목록 보기
88/170

들어가는 말

2021년 카카오 채용연개형 인턴십 코딩테스트에서 나왔던 문제다. level이 1인데 왜 안 풀었는지 의문이다. 그때는 어려워서 안 풀었나? 지금은 풀 수 있는데 ㅎㅎ. 암튼 문자와 숫자가 혼합된 문장이 주어질 때 이를 오로지 숫자로 바꿔서 리턴하는 문제다. 처음 본 순간 map으로 풀면 된다고 생각했다. 실제로 그렇게 풀어서 맞았고.

코드 설명

일단 map m을 zero부터 nine까지 정의한다. key는 문자로 표현된 숫자를 value는 string형 숫자를 넣어줬다.

문자열을 처음부터 끝까지 찾는데, 만일 숫자가 있다면 문자열 a에 넣어준다. 그게 아니면 key에다가 s[i]를 차곡차곡 넣어 문자열을 만들어준다. 그렇게 만든 문자열이 m의 key에 존재한다면 키의 value를 a에 넣어준다(key의 value를 구할 때 조금 헤맸다). 그리고 key를 초기화한다.

마지막으로 문자열로 구한 정답을 stoi()를 이용해 answer에 넣어주면 끝!

코드

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

using namespace std;

int solution(string s) {
    int answer = 0;
    map<string, string> m;
    string key = "";
    string a = "";
    
    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";
    
    for(int i=0; i<s.length(); i++){
        if(48 <= s[i] && s[i] <= 57){
            a = a + s[i];
        }else{
            key = key + s[i];
            if(m.find(key) != m.end()){
                //auto k = m.find(key)->second;
                a = a + m.find(key)->second;
                key = "";
            }
        }
    }
    
    answer = stoi(a);

    return answer;
}

P.s

정규 표현식을 써서 훨씬 간단하게 푼 사람들도 있다. 문자열이 주어졌을 경우는 거의 다 정규식을 쓰라는 팁도 얻었다!

#include<string>
#include<vector>
#include<regex>

using namespace std;

int solution(string s){
	s = regex_replace(s, regex("zero"), "0");
    s = regex_replace(s, regex("one"), "1");
    s = regex_replace(s, regex("two"), "2");
    s = regex_replace(s, regex("three"), "3");
    s = regex_replace(s, regex("four"), "4");
    s = regex_replace(s, regex("five"), "5");
    s = regex_replace(s, regex("six"), "6");
    s = regex_replace(s, regex("seven"), "7");
    s = regex_replace(s, regex("eight"), "8");
    s = regex_replace(s, regex("nine"), "9");
return stoi(s);
}
profile
https://jiwonna52.tistory.com/

0개의 댓글