PROBLEM SOLVING/프로그래머스
프로그래머스 / 숫자 문자열과 영단어
개발자 구리
2022. 1. 17. 22:27
https://programmers.co.kr/learn/courses/30/lessons/81301?language=cpp
코딩테스트 연습 - 숫자 문자열과 영단어
네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다. 다음은 숫자의 일부 자
programmers.co.kr
문제 요약 >
일부 자릿수가 영단어로 표현되어 있는 문자열에서 원래 숫자를 구하자.
풀이 >
o로 시작하면 1, t로 시작하고 그 다음 문자가 w이면 2, 이런 방식으로 문제를 해결했다.
int i, index, answer = 0; 이런식으로 초기화를 하는 경우 index는 0으로 초기화되지 않기 때문에 주의해야한다는 것을 알았다.
다른 사람의 풀이 중에 regex를 사용해서 정규표현식으로 기깔나게 푼 것이 있어서 흥미로웠다.
#include <string>
#include <vector>
#include <cctype>
#include <iostream>
#include <cmath>
using namespace std;
int solution(string s) {
int arr[10] = {-1,};
int i, index = 0, answer = 0;
for (i = 0; i < s.size(); i++)
{
if (isdigit(s[i])) arr[index++] = s[i] - '0';
if (s[i] == 'o')
{
arr[index++] = 1;
i += 2;
}
else if (s[i] == 't' && s[i+1] == 'w')
{
arr[index++] = 2;
i += 2;
}
else if (s[i] == 't' && s[i+1] == 'h')
{
arr[index++] = 3;
i += 4;
}
else if (s[i] == 'f' && s[i+1] == 'o')
{
arr[index++] = 4;
i += 3;
}
else if (s[i] == 'f' && s[i+1] == 'i')
{
arr[index++] = 5;
i += 3;
}
else if (s[i] == 's' && s[i+1] == 'i')
{
arr[index++] = 6;
i += 2;
}
else if (s[i] == 's' && s[i+1] == 'e')
{
arr[index++] = 7;
i += 4;
}
else if (s[i] == 'e')
{
arr[index++] = 8;
i += 4;
}
else if (s[i] == 'n')
{
arr[index++] = 9;
i += 3;
}
else if (s[i] == 'z')
{
arr[index++] = 0;
i += 3;
}
}
for (int i = 0, j = index - 1; i < index; i++, j--)
{
answer += arr[i] * pow(10, j);
}
return answer;
}