[코테] 신규 아이디 추천

이동창·2022년 4월 13일
0

코딩테스트

목록 보기
3/5

my solution

function removeFirstAndLastComma(str) {
    if(str[str.length - 1] === '.')
        str = str.slice(0, str.length - 1)
    
    if(str[0] === '.')
        str = str.slice(1, str.length)
    
    return str
}

function addLastChar(str){
    if(str.length === 0) return 'a'
    if(str.length<3)
		return str + str[str.length - 1].repeat(3 - str.length)
    else
        return str
}

function solution(new_id) {
    const not_allowed = ['~','!','@','#','$','%','^','&','*','(',')','=','+','[','{',']','}',':','?',',','<','>','/']
    
    const str1 = new_id.toLowerCase()
    const str2 = [...str1].filter((e)=>!not_allowed.includes(e)).join('')
    const str3 = [...str2].filter((e,i,s) => s[i] !== '.' || (s[i] === '.' && s[i+1] !== '.')).join('')  
    const str4 = removeFirstAndLastComma(str3)
    const str5 = addLastChar(str4)
    const str6 = removeFirstAndLastComma(str5.slice(0,15))
    const answer = addLastChar(str6)
    
    return answer;
}

not_allowed 를 좀 더 이쁘게 할 수 있는 방법이 없나 생각이 들었고,
[...str1] 와 같이 배열로 만들어서 배열 메소드를 쓰는 것도 좀 어색해보이긴 했는데
아무래도 배열 메소드가 더 범용성이 좋아서 이렇게 해두었다.

아 그리고 처음엔 addLastChar 함수가 재귀로 만들었는데,
이게 성능상 너무 안 좋은 영향을 주는 것 같아서 repeat 메소드로 바꿨다.

other's solution

const solution = (new_id) => {
    const id = new_id
        .toLowerCase()
        .replace(/[^\w\d-_.]/g, '')
        .replace(/\.{2,}/g, '.')
        .replace(/^\.|\.$/g, '')
        .padEnd(1, 'a')
        .slice(0, 15)
        .replace(/^\.|\.$/g, '')        
    return id.padEnd(3, id[id.length-1])
}

말도 안되게 짧아졌다.
replace 메소드와 정규표현식을 이용해, 체이닝으로 구현한 것이 인상적이었다.

다른 풀이 방법들도 있었지만, 이게 제일 간결하다는 생각이 들었고
padEnd를 사용한 것이 가장 인상적인 부분이었다.

성능적 차이가 좀 궁금하다
일단 문자열을 이용해 새로운 배열을 만들어서 배열 메소드를 사용하는 것보다는
공간 복잡도 차이가 발생할 수 밖에 없을 것 같은데
시간 복잡도는 동일한지 조금 궁금하긴 했다.

그렇다면 정규표현식과 padEnd에 대해서 조금 더 알아보자

정규표현식

padEnd

0개의 댓글