끄적끄적
프로그래머스 lv1 [숫자 문자열과 영단어] 본문
2019 카카오 채용연계형 인턴십 문제
출처 : https://programmers.co.kr/learn/courses/30/lessons/81301
코딩테스트 연습 - 숫자 문자열과 영단어
네오와 프로도가 숫자놀이를 하고 있습니다. 네오가 프로도에게 숫자를 건넬 때 일부 자릿수를 영단어로 바꾼 카드를 건네주면 프로도는 원래 숫자를 찾는 게임입니다. 다음은 숫자의 일부 자
programmers.co.kr
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<bits/stdc++.h> | |
using namespace std; | |
int solution(string s) { | |
int answer = 0; | |
s = regex_replace(s, regex("zero"), "0"); | |
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"); | |
answer = stoi(s); | |
return answer; | |
} |
처음에는 if-else 문으로 접근하였는데, 코드가 너무 길어지고 복잡해지는 것 같아 구글링을 해봤다.
regex_replace()함수를 사용하면 좀 더 간단하게 풀 수 있다.
regex_replace 함수는 문자열에서 해당 단어를 찾아 원하는 문자열로 바꿔주는 역할을 한다.
regex_replace(대상 문자열, regex(정규식), 치환 문자열)
-> 대상문자열에서 정규식으로 지정한 문자를 치환 문자열로 변환
또한, #include<bits/stdc++.h>를 사용하면 여러 헤더 파일을 사용할 필요가 없어진다.
자주 사용하는 라이브러리들(string, vector, algorithm...)를 컴파일 하도록 함으로써 번거로움이 줄지만, 그만큼 저장공간이 낭비된다는 단점이 있다.
'코테준비' 카테고리의 다른 글
프로그래머스 lv2 [주식가격] (0) | 2021.10.30 |
---|---|
프로그래머스 lv1 [소수 만들기] (0) | 2021.10.28 |
프로그래머스 lv2 [멀쩡한 사각형] (0) | 2021.10.27 |
프로그래머스 [로또의 최고 순위와 최저 순위] (0) | 2021.10.14 |
프로그래머스 sql - GROUP BY (0) | 2021.10.09 |