개발/알고리즘(코딩테스트)
프로그래머스, 자바스크립트) 2021 카카오 채용연계형 인턴십- 숫자 문자열과 영단어
빔네모
2025. 6. 1. 23:57
숫자 문자열과 영단어
https://school.programmers.co.kr/learn/courses/30/lessons/81301
프로그래머스
SW개발자를 위한 평가, 교육의 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프
programmers.co.kr
풀이
일단 숫자와 매칭되는 문자를 알려주기 위해 Map을 하나 만든다.
그 다음은 replace 함수로 정규식을 이용해 해당 문자가 있다면 매칭되는걸 찾아 변환시켜준다.
최종적으로는 숫자형으로 변환해야 하니 + 연산자로 형변환 시켜 반환한다.
//숫자-문자 매칭
const numberMap = {
zero: "0",
one: "1",
two: "2",
three: "3",
four: "4",
five: "5",
six: "6",
seven: "7",
eight: "8",
nine: "9",
};
function solution(s) {
const result = s.replace(/zero|one|two|three|four|five|six|seven|eight|nine/g, (word) => numberMap[word]);
return + result;
}