알고리즘 문제 풀기
프로그래머스: [3차]파일명 정렬 - javascript(정규식 끝판왕)
Fo_rdang
2024. 4. 11. 11:22
반응형
문제 출처
https://school.programmers.co.kr/learn/courses/30/lessons/17686
프로그래머스
코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.
programmers.co.kr
문제 풀이 힌트
- 파일명을 나누기 세 부분으로
- 그래서 head 기준으로 순서 정하고 (사전순)
- number 순으로 순서 정하고 (앞 0 빼고, 숫자 크기 오름차순)
- 그마저도 같을 때 기존 순서 유지
정답 풀이 코드
function solution(files) {
return files.sort((a, b) => {
// a와 b의 head 부분을 정규 표현식을 사용해 추출하고 소문자로 변환
const headA = a.match(/\D+/)[0].toLowerCase();
const headB = b.match(/\D+/)[0].toLowerCase();
// headA와 headB를 비교하여 정렬 순서를 결정
if (headA < headB) return -1;
if (headA > headB) return 1;
// head가 같을 경우, a와 b의 number 부분을 정규 표현식을 사용해 추출하고 앞의 0을 제거
const numA = a.match(/\d+/)[0].replace(/^0+/, '');
const numB = b.match(/\d+/)[0].replace(/^0+/, '');
// number를 비교하여 정렬 순서를 결정
return numA - numB;
});
}
Only 풀이 코드
function solution(files) {
return files.sort((a,b) => {
const headA = a.match(/\D+/)[0].toLowerCase()
const headB = b.match(/\D+/)[0].toLowerCase()
if(headA < headB) return -1;
if(headA > headB) return 1;
const numA = a.match(/\d+/)[0].replace(/^0+/,'')
const numB = b.match(/\d+/)[0].replace(/^0+/,'')
return numA-numB;
})
}
다른 풀이 코드 1
위 코드랑 거의 같은데, 구조만 바꿔줬다.
function solution(files) {
return files.sort((a,b) => {
const headA = a.match(/\D+/)[0].toLowerCase();
const headB = b.match(/\D+/)[0].toLowerCase();
if(headA === headB){
const numberA = a.match(/\d+/)[0].replace(/^0+/,'');
const numberB = b.match(/\d+/)[0].replace(/^0+/,'');
return numberA - numberB;
}else{
if(headA < headB) return -1;
if(headA > headB) return 1
}
})
}
다른 풀이 코드 2
function solution(files) {
return files.sort((a,b) => {
const headA = a.match(/\D+/)[0].toLowerCase();
const headB = b.match(/\D+/)[0].toLowerCase();
if(headA === headB){
const numberA = a.match(/\d+/)[0].replace(/^0+/,'');
const numberB = b.match(/\d+/)[0].replace(/^0+/,'');
return numberA - numberB;
}else{
return headA.localeCompare(headB) //이 부분이 다름
}
})
}
알고가는 ppoint
1. match
str.match(regexp)
regexp에 일치하는 문자열을 첫번째 요소로 포함하는 `Array`를 반환한다.
2. replace
문자열에서 변경하려는 문자열이 여러번 반복된 경우,
첫번째로 발견한 문자열만 치환
let str = 'apple,banana,banana'
let answer = str.replace('banana','tomato')
console.log(answer)
//'apple,tomato,banana'
대소문자 구분없이 모든 문자열 치환
let str = 'apple,Banana,orange,banana'
let answer = str.replace(/banana/gi, 'tomato')
console.log(answer);
//'apple,tomato,orange,tomato'
3. sort할 때 앞에 return 붙여야 하는 이유
4. charCodeAr()
5. a.localeCompare(b)
6. 문자열 오름차순 sort일 때 return -1, 1에 대해서 헷갈림
반응형