문제
https://school.programmers.co.kr/learn/courses/30/lessons/81301
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
코드
내 풀이
function solution(s) {
const dic = {
'zero':'0',
'one':'1',
'two':'2',
'three':'3',
'four':'4',
'five':'5',
'six':'6',
'seven':'7',
'eight':'8',
'nine':'9'
}
let temp = ''
let answer = ''
for(i of s){
if(!('0'<=i && i<=9)){
temp+=i;
if(temp in dic){
answer+=dic[temp];
temp='';
}
}else answer+=i;
}
return Number(answer);
}
다른 사람 풀이
function solution(s) {
const arr= ['zero','one','two','three','four','five','six','seven','eight','nine']
arr.forEach((item,idx)=>{
s=s.replaceAll(item, idx);
})
return Number(s);
}
정리
String에서 제공하는 replaceAll method를 사용하면 간단하게 풀 수 있는 문제였다.
++
replace vs replaceAll
const s='abc|def|ghi';
console.log(s.replace('|','*')); // abc*def|ghi
console.log(s.replaceAll('|','*')) // abc*def*ghi
replace는 제일 앞쪽에 있는 것만 교체한다.
replaceAll은 모두 교체한다.
참조
https://school.programmers.co.kr/questions/56125
'Programmers' 카테고리의 다른 글
| [프로그래머스] 키패드 누르기 (JS) (0) | 2023.11.20 |
|---|---|
| [프로그래머스] 표 편집 (JS) - 연결리스트 (0) | 2023.11.19 |
| [프로그래머스] 거리두기 확인하기 (JS) - DFS, 2차원 배열 잘 선언하기 (1) | 2023.11.19 |
| [프로그래머스] 입국심사 (JS) - binary search (0) | 2023.11.19 |
| [프로그래머스] 네트워크 (JS) - DFS (0) | 2023.11.17 |