공부 기록

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

by 너나나

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

 

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

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

programmers.co.kr

one4sevneeight -> 1478

23four5six7 -> 234567

1zerotwozero3 -> 10203

이렇게 영어로 된 친구들까지 숫자로 바꿔주는 문제다!!

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

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

int solution(string s) {
    int answer = 0;
    for(iter = number.begin(); iter != number.end(); iter++) {
        int location = s.find(iter->first);
        if(location != -1) {
            s.replace(location, (iter->first).length(), to_string(iter->second));
        }
        if(s.find(iter->first) != -1) {
            iter--;
        }
    }
    answer = stoi(s);
    return answer;
}

좀 무식하게 풀었다!!!! map을 이용해서 각 문자열과 숫자 쌍을 만들었고 iterator로 각 맵을 순회하면서 해당하는 문자열이 있으면 해당 숫자로 바꿔주게 구현했다!!

처음에 if(s.find(iter->first) != -1) { iter--; } 저 부분을 안적으니까 해당 문자열의 첫번째 인덱스만 반환해주는 replace 특징때문에 1zerotwozero3 -> 10203 이렇게 해당하는 문자열이 2개 이상 있는 경우를 처리를 못해서 테스트케이스를 통과하지 않았다!!! 

 

저렇게 풀고 다른사람들 풀이 봤는데 regex_replace(해당 문자열, regex(정규식), 치환 문자열) 함수를 사용해서 간단하게 풀 수 있었다!!!

#include <string>
#include <regex>
using namespace std;

int solution(string s){
    int answer = 0;
    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);
}

C++ 유용한 친구들이 많은데 여러 개 찾아봐야겠다는 생각이 들었땅

'study > 알고리즘' 카테고리의 다른 글

[프로그래머스] 기능개발 C++  (1) 2022.05.11
[프로그래머스] 완주하지 못한 선수 C++  (1) 2022.05.11
[프로그래머스] 신고 결과 받기 C++  (0) 2022.05.09
C++ 백준 11728번  (0) 2021.02.26
C++ 백준 10816번  (0) 2021.02.25

블로그의 정보

공부 기록

너나나

활동하기