1. 조건
주어진 문자열에서
zero, one, two, ..., nine 와 같은 문자를
숫자 0, 1, 2, ..., 9로 바꾸어서 number형태로 return 해주면 된다.
2. 풀이 과정
그냥 딱봐도 정규표현식 쓰라는것같은데
많이 써본 경험이 없어서 이것저것 찾아보느라 시간이 생각 이상으로 오래걸렸다.
그리고 replace라는 고차함수도 처음 활용해 보았다. (기억나는 부분 한정으로...)
추가: 굳이 정규표현식 안써도 되더라... (4번 참고)
3. 내 코드
function solution(s) {
const regexes = [
/zero/gi,
/one/gi,
/two/gi,
/three/gi,
/four/gi,
/five/gi,
/six/gi,
/seven/gi,
/eight/gi,
/nine/gi,
];
regexes.map((regex, idx) => (s = s.replace(regex, idx)));
return parseInt(s, 10);
}
solution("one4seveneight");
solution("23four5six7");
solution("2three45sixseven");
solution("123");
4. 다른 풀이 (정규표현식 X)
function solution(s) {
const words = [
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
];
words.map((word, idx) => (s = s.split(word).join(idx)));
return parseInt(s, 10);
}
solution("one4seveneight");
solution("23four5six7");
solution("2three45sixseven");
solution("123");
'개발이야기 > 알고리즘' 카테고리의 다른 글
[알고리즘] 프로그래머스 햄버거 만들기 (0) | 2023.02.02 |
---|---|
[알고리즘] 프로그래머스 옹알이(2) (0) | 2023.02.01 |
[알고리즘] 프로그래머스 콜라 문제 (0) | 2023.01.30 |
[알고리즘] 프로그래머스 삼총사 (0) | 2023.01.29 |
[알고리즘] 프로그래머스 숫자 짝꿍 (0) | 2023.01.27 |