알고리즘 문제풀이/프로그래머스
[프로그래머스/Level 1] 숫자 문자열과 영단어 (C++)
노력의천재
2021. 7. 26. 13:29
https://programmers.co.kr/learn/courses/30/lessons/81301
코딩테스트 연습 - 숫자 문자열과 영단어
네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다. 다음은 숫자의 일부 자
programmers.co.kr
카카오 기출
"onezerozero" -> 100로 변환해줘야 하는데, "zero"가 두번 나오기 때문에 while문을 사용해야 한다는 점을 주의
알게된 점
1. string의 find 함수를 사용해 특정 단어를 찾으면 그 단어가 시작되는 인덱스를 반환한다. 만약 못찾으면 string::npos를 반환한다.
2. replace(from, 사이즈(길이), to); (from에 find 함수를 사용할 수 있다.)
#include <string>
#include <vector>
using namespace std;
int solution(string s) {
string words[10] = {"zero", "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine"};
for(int i = 0; i < 10; i++) {
while(s.find(words[i]) != string::npos) {
s.replace(s.find(words[i]), words[i].size(), to_string(i));
}
}
return stoi(s);
}
추가 풀이
#include <string>
#include <vector>
#include <regex>
#include <algorithm>
#include <iostream>
using namespace std;
string table[10] = {"zero", "one", "two", "three", "four",
"five", "six", "seven", "eight", "nine"};
int solution(string s) {
for (int i = 0; i < 10; i++) {
s = regex_replace(s, regex(table[i]), to_string(i));
}
return stoi(s);
}
regex, regex_replace 함수를 이용하여 간단하게 풀 수 있는 방법을 발견하였는데, 해당 함수의 활용 빈도가 높아보여 기록해둔다.