📌문제
https://school.programmers.co.kr/learn/courses/30/lessons/81301
🎖️난이도
Level 1
✔️풀이
// sol1) map(dict), isdigit, substr 이용
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <regex>
using namespace std;
int solution1(string s) {
map<string, string> 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";
int idx = 0;
string result = "";
while (idx < s.size()) {
if (isdigit(s[idx])) {
result += s[idx];
idx++;
continue;
}
for (int i = 3; i < 6; i++) { // key는 3~5글자 (ex. "three")
// cf. contains는 c++20부터.. / find : 키 값이 있는지 없는지
if (m.count(s.substr(idx, i))) { // idx로부터 i개 slice
result += m[s.substr(idx, i)];
idx += i;
break;
}
}
}
return stoi(result);
}
// sol2) regex (REGular EXpression 이용)
#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <regex>
using namespace std;
int solution2(string s) {
//s.replace(s.find("zero"), 4, "0"); // 이건 find 해서 없을 경우 error...
s = regex_replace(s, regex("zero"), "0"); // s에서 "zero"를 "0"으로 replace한 결과 s를 return
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);
}
🧠노트
-
🔍참고
[ map.count() ]
- map : python의 dict와 같음
- count()
- contains() => c++20부터
[ string.substr() ]
- 문자열 slice
[ regex.regex_replace() ]
- #include <regex> : REGular EXpression
- regex_replace() : python의 replace()와 같음, find해서 없어도 넘어감
- replace() : 위와 다르게, find해서 없으면 error!
'[ 알고리즘 ] > Implementation' 카테고리의 다른 글
[프로그래머스/C++] 소수 찾기 (0) | 2022.10.10 |
---|---|
[프로그래머스/C++] 폰켓몬 (0) | 2022.10.10 |
[프로그래머스/C++] 2016년 (0) | 2022.10.10 |
[프로그래머스] 교점에 별 만들기 (0) | 2022.10.07 |
[프로그래머스] 스킬트리 (0) | 2022.10.07 |