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

jathazp·2021년 8월 24일
0

algorithm

목록 보기
52/57

문제링크

https://programmers.co.kr/learn/courses/30/lessons/81301?language=cpp

문제

풀이

  1. 구현
    문자열을 한글자씩 돌면서 숫자인 경우는 ans에 그대로 합쳐주고 알파벳인 경우는 while문을 이용해 zero~nine 이 완성될때까지 temp 변수에 저장한다. zero~nine이 완성되고 나면 ans에 해당하는 숫자를 합쳐준다
  2. C++ 정규식 regex 라이브러리 이용
    regex_replace를 이용해 알파벳에 해당하는 부분을 숫자로 바꿔준다.

코드

  1. 구현
#include <string>
#include <vector>
#include <string>
using namespace std;

string parsing(string num_alpha) {
    if (num_alpha == "zero") return "0";
    if (num_alpha == "one") return "1";
    if (num_alpha == "two") return "2";
    if (num_alpha == "three") return "3";
    if (num_alpha == "four") return "4";
    if (num_alpha == "five") return "5";
    if (num_alpha == "six") return "6";
    if (num_alpha == "seven") return "7";
    if (num_alpha == "eight") return "8";
    if (num_alpha == "nine") return "9";
}

bool check(string num_alpha) {
    if (num_alpha == "zero" ||
        num_alpha == "one" ||
        num_alpha == "two" ||
        num_alpha == "three" ||
        num_alpha == "four" ||
        num_alpha == "five" ||
        num_alpha == "six" ||
        num_alpha == "seven" ||
        num_alpha == "eight" ||
        num_alpha == "nine") return true;
    else return false;
}

int solution(string s) {
    string ans = "";
    for (int i = 0; i < s.size(); i++) {
        if (s[i] >= '0' && s[i] <= '9') {
            ans += s[i];
            continue;
        }
        
        string num_alpha = "";
        while (i != s.size() && !check(num_alpha)) {
            num_alpha += s[i];
            i++;
        }
        i--;
        ans += parsing(num_alpha);
    }

    return stoi(ans);
}
  1. regex 헤더
#include <string>
#include <regex>
#include <vector>
#include <string>
using namespace std;

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

후기

C++ 에서도 정규식 사용이 가능한걸 처음알았다 ..!
C++ 의 정규식 사용에 대해 더 공부해보자

ref) http://www.jiniya.net/ng/2017/11/regex/
https://ansohxxn.github.io/cpp/chapter18-5/
https://m.blog.naver.com/PostView.naver?isHttpsRedirect=true&blogId=jinhan814&logNo=222090272427
https://modoocode.com/303

0개의 댓글