본문 바로가기

ALGORITHM/문자열

[Swift] 프로그래머스 Lv1. 신규 아이디 추천

https://programmers.co.kr/learn/courses/30/lessons/72410

 

코딩테스트 연습 - 신규 아이디 추천

카카오에 입사한 신입 개발자 네오는 "카카오계정개발팀"에 배치되어, 카카오 서비스에 가입하는 유저들의 아이디를 생성하는 업무를 담당하게 되었습니다. "네오"에게 주어진 첫 업무는 새로

programmers.co.kr

 

정규식으로 풀어보려했지만 그냥 구현하고 싶어 구현 하다가?

filter 에 조건을 여러개 넣었더니 시간안에 타입체크 할 수 없다고 쪼개보라고 에러가 발생했다.

 

ID = ID.filter { ("a" <= $0 && $0 <= "z") || ("0" <= $0 && $0 <= "9") || $0 == "-" || $0 == "_" || $0 == "." }

 

error: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions

ID.removeAll(where: { !(("a" <= $0 && $0 <= "z") || ("0" <= $0 && $0 <= "9") || $0 == "-" || $0 == "_" || $0 == ".") })

 

/Solution/Sources/Solution/Solution.swift:8:8: error: the compiler is unable to type-check this expression in reasonable time; try breaking up the expression into distinct sub-expressions
ID = ID.filter {

 

 

하지만 각각의 filter 로 줄이기엔 위에서 filter 되는 순간 나머지 필터링할게 모두 삭제되기 때문에..

if문으로 바꿔서 해결하였다.

 

그런데 다른 분들의 풀이를 보니 Character 에 isLetter 함수와 isNumber 함수가 있는 것을 발견하고 변경하였다.

 

전체코드

import Foundation

func makeNewID(_ ID: String) -> String {
    
    // 1
    let ID = ID.lowercased()
    
    // 2
    var newID = ""
    for s in ID {
        if s.isLetter || s.isNumber || s == "-" || s == "_" || s == "." {
            newID.append(s)
        }
    }
    
    // 3
    while newID.contains("..") {
        newID = newID.replacingOccurrences(of: "..", with: ".")
    }
    
    // 4
    while newID.hasPrefix(".") { newID.removeFirst() }
    while newID.hasSuffix(".") { newID.removeLast() }
    
    // 5
    if newID == "" { newID.append("a") }
    
    // 6
    if 16 <= newID.count {
        let index = newID.index(newID.startIndex, offsetBy: 15)
        newID = String(newID[newID.startIndex..<index])
        while newID.hasSuffix(".") { newID.removeLast() }
    }
    
    // 7
    if newID.count <= 2 {
        while newID.count < 3 {
            newID += String(newID.last!)
        }
    }
    return newID
}

func solution(_ new_id:String) -> String {
    return makeNewID(new_id)
}

print(solution("...!@BaT#*..y.abcdefghijklm"))
print(solution("z-+.^."))
print(solution("=.="))
print(solution("123_.def"))
print(solution("abcdefghijklmn.p"))