네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다.
다음은 숫자의 일부 자릿수를 영단어로 바꾸는 예시입니다.
1478 → "one4seveneight"
234567 → "23four5six7"
10203 → "1zerotwozero3"
이렇게 숫자의 일부 자릿수가 영단어로 바뀌어졌거나, 혹은 바뀌지 않고 그대로인 문자열 s가 매개변수로 주어집니다. s가 의미하는 원래 숫자를 return 하도록 solution 함수를 완성해주세요.
문자를 대응되는 숫자로 바꿔주기만 하면 되는 간단한 문제였다.
문제풀이
이전에 파이썬으로 풀었던 문제지만 string을 c++에서 다루는 게 쉽지만은 않아 한번 더 풀었다.
처음에는 Enum 을 활용해 switch-case 문을 활용해보려 했지만, 예외처리 하는 과정에서 번거로워서 그냥 if-else 문으로 처리했다.
파이썬에서는 dictionary를 사용해서 풀이 했다.
기본적으로 모든 문자를 순회하며 숫자가 아니라면 임시로 저장해줬다. 임시로 저장한 string 의 size 가 3이 되면 대응되는 영단어가 있는지 체크하고 있다면 숫자로 리턴받아 답에 char로 더해줬다.
코드
파이썬
answer_sheet = {'zero': '0', 'one': '1', 'two': '2', 'three': '3', 'four': '4', 'five': '5', 'six': '6', 'seven': '7', 'eight': '8', 'nine': '9'}
def solution(s):
answer = ''
tmp = ''
for i in s:
if i.isdigit():
answer += i
else:
tmp += i
if answer_sheet.get(tmp, 0) != 0:
answer += answer_sheet[tmp]
tmp = ''
return int(answer)
C++
#include <string>
#include <vector>
#include <cctype>
using namespace std;
int answer_sheet(string s) {
if (s == "zero") return 0;
else if (s == "one") return 1;
else if (s == "two") return 2;
else if (s == "three") return 3;
else if (s == "four") return 4;
else if (s == "five") return 5;
else if (s == "six") return 6;
else if (s == "seven") return 7;
else if (s == "eight") return 8;
else if (s == "nine") return 9;
else return -1;
}
int solution(string s) {
string answer = "";
string tmp="";
for (char c: s) {
if (isdigit(c)) {
answer += c;
continue;
}
tmp += c;
if (tmp.size() > 2) {
int ck = answer_sheet(tmp);
if (ck > -1) {
tmp = "";
answer += '0' + ck;
}
}
}
int res = stoi(answer);
return res;
}